Software:Command-line argument parsing

From HandWiki
Short description: Programming languages parsing of command-line arguments
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

Parsing methods

Many languages offer functionality for argument parsing. For example, the C POSIX library provides getopt(), Python offers a module called argparse[1], while C# provides a namespace System.CommandLine[2]. 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

AWK

AWK uses ARGV also.

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

C

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

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++

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.[5] Boost provides a class boost::program_options::command_line_parser.[6] 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.[7]

C#

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.[8]

D

The D programming language provides a module std.getopt.

Go

Go provides the flag package for argument parsing.

Haskell

Haskell provides the library System.Console.GetOpt.

Java

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.[9] There is also the gnu.getopt library, ported from GNU getopt.

Kotlin

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

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

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

PHP uses argc as a count of arguments and argv as an array containing the values of the arguments.[11][12] 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().[13]

Python

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.[1]

Racket

Racket uses a current-command-line-arguments parameter, and provides a racket/cmdline[14] 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

Rexx uses arg, e.g.:

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

Rust

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().[15]

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.[16]

JavaScript

Node.js

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

// 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.[18]

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

Bun

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

console.log(Bun.argv);

Deno

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

console.log(Deno.args);

References

  1. 1.0 1.1 "argparse — Parser for command-line options, arguments and sub-commands". Python v3.10.0 documentation. https://docs.python.org/3/library/argparse.html. Retrieved 15 October 2021. 
  2. Microsoft Corporation. "System.CommandLine overview". Microsoft Learn. https://learn.microsoft.com/en-us/dotnet/standard/commandline/. 
  3. "The C Book — Arguments to main". Publications.gbdirect.co.uk. http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html. Retrieved 2010-05-31. 
  4. An example of parsing C arguments and options
  5. POCO Project. "Class Poco::Util::OptionProcessor". POCO C++ Libraries. https://docs.pocoproject.org/current/Poco.Util.OptionProcessor.html. 
  6. Vladimir Prus. "Chapter 28. Boost.Program_options". Boost C++ Libraries. https://www.boost.org/doc/libs/latest/doc/html/program_options.html. 
  7. p-ranav. "argparse". GitHub. https://github.com/p-ranav/argparse. 
  8. "System.CommandLine overview - .NET" (in en-us). https://learn.microsoft.com/en-us/dotnet/standard/commandline/. 
  9. Apache Commons (8 November 2025). "Apache Commons CLI". Apache Commons. https://commons.apache.org/proper/commons-cli/. 
  10. "Kotlin: Basic syntax". https://kotlinlang.org/docs/basic-syntax.html#program-entry-point. Retrieved 2022-05-13. 
  11. "PHP Manual". PHP. http://php.net/manual/en/reserved.variables.argv.php. Retrieved 2010-05-31. 
  12. wikibooks:PHP Programming/CLI
  13. "PHP: Getopt - Manual". https://php.net/getopt. 
  14. The Racket reference manual, Command-Line Parsing
  15. "Accepting Command Line Arguments - The Rust Programming Language". https://doc.rust-lang.org/book/ch12-01-accepting-command-line-arguments.html. 
  16. "Crate clap". clap. 19 November 2025. https://docs.rs/clap/latest/clap/. 
  17. "process.argv". Node.js v10.16.3 Documentation. https://nodejs.org/docs/latest-v10.x/api/process.html#process_process_argv. Retrieved 3 October 2019. 
  18. "How to parse command line arguments". Node.js Foundation Documentation. https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/. Retrieved 3 October 2019. 
  19. "Parse command-line arguments | Bun Examples" (in en). https://bun.sh/guides/process/argv. 
  20. "Deno.args". https://docs.deno.com/api/deno/~/Deno.args. 
  21. "parseArgs from parse-args - @std/cli - JSR" (in en). https://jsr.io/@std/cli/doc/parse-args/~/parseArgs.