Command Line Arguments in Co-array Fortran

Command-line arguments are a common way to parameterize execution of programs. For example, ./program arg1 arg2 uses arg1 and arg2 as arguments to the program executable.

program main
  use iso_fortran_env
  implicit none
  
  character(len=:), allocatable :: arg
  integer :: i, num_args
  
  ! Get the number of command-line arguments
  num_args = command_argument_count()
  
  ! Print all arguments, including the program name
  do i = 0, num_args
    call get_command_argument(i, length=len)
    allocate(character(len) :: arg)
    call get_command_argument(i, value=arg)
    print *, arg
    deallocate(arg)
  end do
  
  ! Print arguments without the program name
  do i = 1, num_args
    call get_command_argument(i, length=len)
    allocate(character(len) :: arg)
    call get_command_argument(i, value=arg)
    print *, arg
    deallocate(arg)
  end do
  
  ! Get individual argument (4th argument, if it exists)
  if (num_args >= 3) then
    call get_command_argument(3, length=len)
    allocate(character(len) :: arg)
    call get_command_argument(3, value=arg)
    print *, arg
    deallocate(arg)
  else
    print *, "Not enough arguments provided"
  end if
  
end program main

In Fortran, we use the command_argument_count() function to get the number of command-line arguments, and get_command_argument() to retrieve individual arguments. The first argument (index 0) is the program name.

To experiment with command-line arguments, compile the program first:

$ gfortran -o command_line_args command_line_args.f90
$ ./command_line_args a b c d
./command_line_args
a
b
c
d
a
b
c
d
c

Note that Fortran arrays are typically 1-indexed, but command-line arguments are 0-indexed (with 0 being the program name). We’ve adjusted our code to account for this.

Next, we’ll look at more advanced command-line processing with additional Fortran features.