Command-line argument parsing

Last updated

Different command-line argument parsing methods are used by different programming languages to parse command-line arguments.

Contents

Programming languages

C

C uses argv to process command-line arguments. [1] [2]

An example of C argument parsing would be:

#include<stdio.h>intmain(intargc,char*argv[]){for(inti=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.

importstd;usingstd::string;usingstd::vector;intmain(intargc,char*argv[]){vector<string>args(argv,argv+argc);for(conststring&s:args){std::println("{}",s);}}

C#

An example of C# argument parsing would be:

classReadArgs{staticvoidMain(string[]args){foreach(stringarginargs){Console.WriteLine(arg);}}}

Java

An example of Java argument parsing would be:

publicclassReadArgs{publicstaticvoidmain(String[]args){for(Strings:args){System.out.println(s);}}}

Kotlin

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

funmain(args:Array<String>)=println(args.joinToString())
funmain(args:Array<String>)=println(args.contentToString())
funmain(args:Array<String>){for(arginargs){println(arg)}}

Perl

Perl uses @ARGV.

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

or

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

AWK

AWK uses ARGV also.

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

PHP

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

$args=parseArgs($argv);echogetArg($args,"foo");functionparseArgs(array$args):array{foreach($argsas$arg){$tmp=explode(":",$arg,2);if($arg[0]==="-"){$args[substr($tmp[0],1)]=$tmp[1];}}return$args;}functiongetArg(array$args,string$arg):string|bool{if(isset($args[$arg])){return$args[$arg];}returnfalse;}

PHP can also use getopt(). [6]

Python

Python uses sys.argv, e.g.:

importsysif__name__=="__main__":forarginsys.argv:printarg

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

Racket

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

#lang racket(requireracket/cmdline)(definesmile?(make-parameter#t))(definenose?(make-parameter#false))(defineeyes(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"(eyeschar)])(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-nfe88-(

Rexx

Rexx uses arg, e.g.:

doi=1towords(arg(1))sayword(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(). [9]

usestd::env;fnmain(){letargs:Vec<String>=env::args().collect();letquery:&String=&args[1];letfile_path:&String=&args[2];println!("Searching for {}",query);println!("In file {}",file_path);}

JavaScript

Node.js

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

// argv.jsconsole.log(process.argv);
$nodeargv.jsonetwothreefourfive ['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. [11]

// process-args.jsconsole.log(process.argv.slice(2));
$nodeprocess-args.jsonetwo=threefour ['one', 'two=three', 'four']

Bun

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

console.log(Bun.argv);

Deno

JavaScript written for Deno use Deno.args [13] and the parseArgs function. [14]

console.log(Deno.args);

References

  1. "The C Book — Arguments to main". Publications.gbdirect.co.uk. Retrieved 2010-05-31.
  2. An example of parsing C arguments and options
  3. "Kotlin: Basic syntax" . Retrieved 2022-05-13.
  4. "PHP Manual". PHP. Retrieved 2010-05-31.
  5. wikibooks:PHP Programming/CLI
  6. "PHP: Getopt - Manual".
  7. "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.
  8. The Racket reference manual, Command-Line Parsing
  9. "Accepting Command Line Arguments - The Rust Programming Language". doc.rust-lang.org. Retrieved 22 December 2022.
  10. "process.argv". Node.js v10.16.3 Documentation. Retrieved 3 October 2019.
  11. "How to parse command line arguments". Node.js Foundation Documentation. Retrieved 3 October 2019.
  12. "Parse command-line arguments | Bun Examples". Bun.
  13. "Deno.args". docs.deno.com.
  14. "parseArgs from parse-args - @std/cli - JSR". jsr.io.