Command-Line Arguments

Modern Fortran compilers provide the intrinsic get_command_argument() routine to read command-line arguments. An example that shows how to utilise this routine is given by Jason Blevins. A simplified version is listed below.

! cmdline.f90
program cmdline
    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)', ''
            print '(a)', '  -v, --version     print version information and exit'
            print '(a)', '  -h, --help        print usage information and exit'
        end subroutine print_help
end program cmdline

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

! cmdopt.f90
program cmdopt
    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 cmdopt

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