Command-Line Arguments

Modern Fortran compilers provide the intrinsic get_command_argument() routine to read command-line arguments, as this example shows:

! cmdline.f90
program main
    implicit none
    character(len=*), parameter :: version = '1.0'
    character(len=32)           :: arg
    integer                     :: i

    do i = 1, command_argument_count()
        call get_command_argument(i, arg)

        select case (arg)
            case ('-v', '--version')
                print '(2a)', 'version ', version
                call exit(0)
            case ('-h', '--help')
                call print_help()
                call exit(0)
            case default
                print '(2a, /)', 'Unrecognized command-line option: ', arg
                call print_help()
                call exit(0)
        end select
    end do

    print '(a)', 'Hello, World!'

        subroutine print_help()
            print '(a, /)', 'command-line options:'
            print '(a)',    '  -v, --version     print version information and exit'
            print '(a)',    '  -h, --help        print usage information and exit'
        end subroutine print_help
end program main

Running the program with command-line arguments outputs additional information:

$ gfortran7 -Wl,-rpath=/usr/local/lib/gcc7/ -o cmdline cmdline.f90
$ ./cmdline --help
command-line options:

  -v, --version     print version information and exit
  -h, --help        print usage information and exit

This approach lacks functionality to read complex options with additional arguments. The Fortran Wiki lists several mature libraries for this purpose. For instance, the f90getopt module allows short and long arguments:

! cmdopt.f90
program main
    use :: f90getopt
    implicit none
    character(len=*), parameter :: version = '1.0'
    integer                     :: attempts = 1
    type(option_s)              :: opts(2)

    opts(1) = option_s('attempts', .true.,  'a')
    opts(2) = option_s('version',  .false., 'v')

        select case (getopt('a:v', opts))
            case (char(0))
            case ('g')
                read (optarg, '(i3)') attempts
            case ('v')
                print '(a, f3.1)', 'version ', version
                call exit(0)
        end select
    end do

    print '(a, i3)', 'number of attempts: ', attempts
end program main

Compile the example with:

$ gfortran7 -c f90getopt.f90
$ gfortran7 -Wl,-rpath=/usr/local/lib/gcc7/ -o cmdopt cmdopt.f90 f90getopt.o
$ ./cmdopt --version
version 1.0