Command-Line Arguments

Modern Fortran compilers, like GNU Fortran, 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')
                write (*, '(2a)') 'version ', VERSION
                call exit(0)
            case ('-h', '--help')
                call print_help()
                call exit(0)
            case default
                print '(a, a, /)', 'Unrecognized command-line option: ', arg
                call print_help()
                call exit(0)
        end select
    end do

    write (*, '(a)') 'Hello, World!'

        subroutine print_help()
            write (*, '(a)') 'command-line options:'
            write (*, '(a)') ''
            write (*, '(a)') '  -v, --version     print version information and exit'
            write (*, '(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 supports additional 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')
                write (*, '(a, f3.1)') 'version ', VERSION
                call exit(0)
        end select
    end do

    write (*, '(*, i3)') 'number of attempts: ', attempts
end program cmdopt

Compile the example with:

$ gfortran7 -c f90getopt.f90
$ gfortran7 -o cmdopt cmdopt.f90 f90getopt.o
$ ./cmdopt --version
version 0.1