Command-line arguments

Count them

Command_argument_count reports how many arguments followed the program name. The program name itself is not counted. Use the count to decide whether enough input was given.

program count_demo implicit none integer :: n n = command_argument_count() print *, n end program count_demo

Get by index

Get_command_argument copies one argument into a character variable by index, starting at 1. Length and status tell you the true size and whether the index existed. Always test status before using the value.

program get_demo implicit none character(len=256) :: arg integer :: L, stat call get_command_argument(1, arg, length=L, status=stat) if (stat == 0) write(*, "(a)") trim(arg(1:L)) end program get_demo

Parse numbers

Arguments arrive as text, so read them with an internal read to convert to numbers. Iostat reports conversion failures without stopping the program. Fall back to a default when parsing fails.

program parse_demo implicit none character(len=256) :: arg integer :: n = 0 integer :: ios call get_command_argument(1, arg, status=ios) if (ios == 0) read(arg, *, iostat=ios) n if (ios /= 0) n = 42 print *, n end program parse_demo

Print usage

Print a short usage message when the count is wrong, then stop. Name the program and list each expected argument in order. Clear usage text saves users from guessing after a mistyped command.

program usage_demo implicit none integer :: n n = command_argument_count() if (n < 2) then write(*, "(a)") "usage: average n1 n2" stop 1 end if end program usage_demo

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev