Command-line argument parsing

An MS-DOS command line, illustrating parsing into command and arguments

Command-line argument parsing refers to methods used in a programming language to parse command-line arguments.

Command-line options

[edit]

A command-line option or simply option (also known as a flag or switch) modifies the operation of a command; the effect is determined by the command's program. Options follow the command name on the command line, separated by, e.g., commas, spaces. Separators are not always required, such as Dir/? and DIR /? in DOS, which have the same effect[1] of listing the DIR command's available options, whereas dir --help (in many versions of Unix) does require the option to be preceded by at least one space (and is case-sensitive).

The format of options varies widely between operating systems. In most cases, the syntax is by convention rather than an operating system requirement; the entire command line is simply a string passed to a program, which can process it in any way the programmer wants, so long as the interpreter can tell where the command name ends and its arguments and options begin.

A few representative samples of command-line options, most relating to listing files in a directory, to illustrate some conventions:

Operating system Command Valid alternative Notes
OpenVMS directory/owner Dir /Owner instruct the directory command to also display the ownership of the files.
Note the Directory command name is not case sensitive, and can be abbreviated to as few letters as required to remain unique.
Windows DIR/Q/O:S d* dir /q d* /o:s display ownership of files whose names begin with d (or D), sorted by size, smallest first.
Note spaces around argument d* are required.
Unix-like systems ls -lS D* ls -S -l D* display in long format files and directories whose names begin with D (but not d), sorted by size (largest first).
Note spaces are required around all arguments and options, but some can be run together, e.g. -lS is the same as -l -S.
Data General RDOS CLI list/e/s 04-26-80/b List /S/E 4-26-80/B list every attribute for files created before 26 April 1980.
Note the /B at the end of the date argument is a local switch, that modifies the meaning of that argument, while /S and /E are global switches, i.e. apply to the whole command.
VM/CMS CLI LISTFILE (FULLDATE) l(ful includes the date the file was last written in the list.
Note the LISTFILE command name is not case sensitive, and can be abbreviated to as few letters as required to remain unique.
OS/360 operator commands START TAPERDR,DSNAME=FOO.BAR S TAPERDR,DSN=FOO.BAR Start the procedure named TAPERDR with the supplied data set name
TSO LISTCAT LEVEL(FOO) MEMBERS LISTC L(FOO) M List datasets at specified index level and list members for each PDS.
SEND 'text' USER(FOO) SE 'text' U(FOO) Send message to specified user
Command-line argument parsing is used to parse the arguments of a program, and such functionality is offered in various languages. For example, getopt() is in the C POSIX library for parsing arguments.

Parsing methods

[edit]

Many languages offer functionality for argument parsing. For example, the C POSIX library provides getopt(), Python offers a module called argparse[2], while C# provides a namespace System.CommandLine[3]. In others, they are not bundled in the standard library, but rather must be used through third-party libraries.

In many languages, particularly C-derived languages, arguments are accessed through the parameters of the main() method. For example, in C and C++, the main method has signature int main(int argc, char* argv[]);, where argc is the number of arguments plus the name of the program, and argv is an array of C-strings where argv[0] is the name of the program. In Java and C#, the main() method instead takes one parameter args of type String[] (an array of strings). Meanwhile, in some other languages, such as Rust, command-line arguments are accessed by a method std::env::args(), allowing a global point of access rather than having to be obtained from main().

In different programming languages

[edit]

AWK

[edit]

AWK uses ARGV also.

BEGIN {
   for ( i = 0; i < ARGC; i++ )
   {
       print ARGV[i]
   }
}

C

[edit]

C uses argv to process command-line arguments.[4][5]

An example of C argument parsing would be:

#include <stdio.h>

int main(int argc, char* argv[]) {
    for (int i = 0; i < argc; ++i) {
        printf("%s\n", argv[count]);
    }
}

C POSIX library also has functions called getopt() and getopt_long().

C++

[edit]

C++ accesses arguments the same way as C.

import std;

using std::string;
using std::vector;

int main(int argc, char* argv[]) {
    vector<string> args(argv, argv + argc);
    for (const string& s: args) {
        std::println("{}", s);
    }
}

The POCO C++ Libraries offer a class Poco::Util::OptionProcessor for parsing command-line arguments.[6] Boost provides a class boost::program_options::command_line_parser.[7] Meanwhile, Google has a library called gflags. There is also a argparse library for C++17+ offers a similar API for argument parsing to Python argparse.[8]

C#

[edit]

An example of C# argument parsing would be:

class ReadArgs
{
    static void Main(string[] args)
    {
        foreach (string arg in args)
        {
            Console.WriteLine(arg);
        }
    }
}

C# provides the System.CommandLine namespace for advanced command-line argument parsing.[9]

D

[edit]

The D programming language provides a module std.getopt.

Go

[edit]

Go provides the flag package for argument parsing.

Haskell

[edit]

Haskell provides the library System.Console.GetOpt.

Java

[edit]

An example of Java argument parsing would be:

public class ReadArgs {
    public static void main(String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

The Apache Commons library org.apache.commons.cli provides command-line argument parsing capabilities.[10] There is also the gnu.getopt library, ported from GNU getopt.

Kotlin

[edit]

Here are some possible ways to print arguments in Kotlin:[11]

fun main(args: Array<String>) = println(args.joinToString())
fun main(args: Array<String>) = println(args.contentToString())
fun main(args: Array<String>) {
    for (arg in args) {
        println(arg)
    }
}

Perl

[edit]

Perl uses @ARGV.

foreach $arg (@ARGV)
{
    print $arg;
}

or

foreach $argnum (0 .. $#ARGV)
{
    print $ARGV[$argnum];
}

There is also Getopt::Long and Getopt::Std for argument parsing.

PHP

[edit]

PHP uses argc as a count of arguments and argv as an array containing the values of the arguments.[12][13] To create an array from command-line arguments in the -foo:bar format, the following might be used:

$args = parseArgs($argv);
echo getArg($args, "foo");

function parseArgs(array $args): array {
    foreach ($args as $arg) {
        $tmp = explode(":", $arg, 2);
        if ($arg[0] === "-") {
            $args[substr($tmp[0], 1)] = $tmp[1];
        }
    }
    return $args;
}

function getArg(array $args, string $arg): string | bool {
    if (isset($args[$arg])) {
        return $args[$arg];
    }
    return false;
}

PHP can also use getopt().[14]

Python

[edit]

Python uses sys.argv, e.g.:

import sys

if __name__ == "__main__":
    for arg in sys.argv:
        print(arg)

Python also has a module called argparse in the standard library for parsing command-line arguments.[2]

Racket

[edit]

Racket uses a current-command-line-arguments parameter, and provides a racket/cmdline[15] library for parsing these arguments. Example:

#lang racket

(require racket/cmdline)

(define smile? (make-parameter #t))
(define nose?  (make-parameter #false))
(define eyes   (make-parameter ":"))

(command-line #:program "emoticon"

              #:once-any ; the following two are mutually exclusive
              [("-s" "--smile") "smile mode" (smile? #true)]
              [("-f" "--frown") "frown mode" (smile? #false)]

              #:once-each
              [("-n" "--nose") "add a nose"  (nose? #true)]
              [("-e" "--eyes") char "use <char> for the eyes" (eyes char)])

(printf "~a~a~a\n"
        (eyes)
        (if (nose?) "-" "")
        (if (smile?) ")" "("))

The library parses long and short flags, handles arguments, allows combining short flags, and handles -h and --help automatically:

$ racket /tmp/c -nfe 8
8-(

Rexx

[edit]

Rexx uses arg, e.g.:

do i=1 to words(arg(1))
	say word(arg(1), i)
end

Rust

[edit]

Rather than being part of the parameters of main() (like other C-style languages), in Rust the args are in std::env::args(), which returns a std::env::Args and is converted to a Vec<String> with .collect().[16]

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();

    let query: &String = &args[1];
    let file_path: &String = &args[2];

    println!("Searching for {}", query);
    println!("In file {}", file_path);
}

A popular Rust library for command-line argument parsing is clap.[17]

JavaScript

[edit]

Node.js

[edit]

JavaScript programs written for Node.js use the process.argv global variable.[18]

// argv.js
console.log(process.argv);
$ node argv.js one two three four five
[ 'node',
  '/home/avian/argvdemo/argv.js',
  'one',
  'two',
  'three',
  'four',
  'five' ]

Node.js programs are invoked by running the interpreter node interpreter with a given file, so the first two arguments will be node and the name of the JavaScript source file. It is often useful to extract the rest of the arguments by slicing a sub-array from process.argv.[19]

// process-args.js
console.log(process.argv.slice(2));
$ node process-args.js one two=three four
[ 
  'one',
  'two=three',
  'four' ]

Bun

[edit]

JavaScript written for Bun use Bun.argv and the util.parseArgs function.[20]

console.log(Bun.argv);

Deno

[edit]

JavaScript written for Deno use Deno.args[21] and the parseArgs function.[22]

console.log(Deno.args);

References

[edit]
  1. ^ Paul, Matthias R. (1997-07-30). "NWDOS-TIPs – Tips & Tricks rund um Novell DOS 7, mit Blick auf undokumentierte Details, Bugs und Workarounds". MPDOSTIP. Release 157 (in German) (3 ed.). Archived from the original on 2017-09-10. Retrieved 2014-09-06. (NB. NWDOSTIP.TXT is a comprehensive work on Novell DOS 7 and OpenDOS 7.01, including the description of many undocumented features and internals. It is part of the author's yet larger MPDOSTIP.ZIP collection maintained up to 2001 and distributed on many sites at the time. The provided link points to a HTML-converted older version of the NWDOSTIP.TXT file.)
  2. ^ a b "argparse — Parser for command-line options, arguments and sub-commands". Python v3.10.0 documentation. Archived from the original on 2012-11-01. Retrieved 15 October 2021.
  3. ^ Microsoft Corporation. "System.CommandLine overview". learn.microsoft.com. Microsoft Learn. Retrieved 6 December 2025.
  4. ^ "The C Book — Arguments to main". Publications.gbdirect.co.uk. Retrieved 2010-05-31.
  5. ^ An example of parsing C arguments and options
  6. ^ POCO Project. "Class Poco::Util::OptionProcessor". docs.pocoproject.org. POCO C++ Libraries. Retrieved 6 December 2025.
  7. ^ Vladimir Prus. "Chapter 28. Boost.Program_options". boost.org/doc. Boost C++ Libraries. Retrieved 6 December 2025.
  8. ^ p-ranav. "argparse". github.com. GitHub. Retrieved 6 December 2025.
  9. ^ "System.CommandLine overview - .NET". learn.microsoft.com. Retrieved 6 December 2025.
  10. ^ Apache Commons (8 November 2025). "Apache Commons CLI". commons.apache.org. Apache Commons.
  11. ^ "Kotlin: Basic syntax". Retrieved 2022-05-13.
  12. ^ "PHP Manual". PHP. Retrieved 2010-05-31.
  13. ^ wikibooks:PHP Programming/CLI
  14. ^ "PHP: Getopt - Manual".
  15. ^ The Racket reference manual, Command-Line Parsing
  16. ^ "Accepting Command Line Arguments - The Rust Programming Language". doc.rust-lang.org. Retrieved 22 December 2022.
  17. ^ "Crate clap". docs.rs. clap. 19 November 2025.
  18. ^ "process.argv". Node.js v10.16.3 Documentation. Retrieved 3 October 2019.
  19. ^ "How to parse command line arguments". Node.js Foundation Documentation. Archived from the original on 17 March 2020. Retrieved 3 October 2019.
  20. ^ "Parse command-line arguments | Bun Examples". Bun.
  21. ^ "Deno.args". docs.deno.com.
  22. ^ "parseArgs from parse-args - @std/cli - JSR". jsr.io.