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[]){intcount;for(count=0;count<argc;count++)puts(argv[count]);}

C also has functions called getopt and getopt_long.

C#

An example of C# argument parsing would be:

classProgram{staticvoidMain(string[]args){foreach(vararginargs)Console.WriteLine(arg);}}

Java

An example of Java argument parsing would be:

publicclassEcho{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)GT{print$arg;}

FT

or

foreach$argnum(0..$#ARGV)ST{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){foreach($argsas$arg){$tmp=explode(":",$arg,2);if($arg[0]==="-"){$args[substr($tmp[0],1)]=$tmp[1];}}return$args;}functiongetArg(array$args,string$arg){if(isset($args[$arg])){return$args[$arg];}returnfalse;}

PHP can also use getopt(). [6]

Python

Python uses sys.argv, e.g.:

importsysforarginsys.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

The args are in env::args(). [9]

usestd::env;fnmain(){letargs: Vec<String>=env::args().collect();letquery=&args[1];letfile_path=&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 (software)|Deno] use Deno.args [13] and the parseArgs function. [14]

console.log(Deno.args);

Related Research Articles

<span class="mw-page-title-main">Quine (computing)</span> Self-replicating program

A quine is a computer program that takes no input and produces a copy of its own source code as its only output. The standard terms for these programs in the computability theory and computer science literature are "self-replicating programs", "self-reproducing programs", and "self-copying programs".

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

In computer programming, standard streams are preconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr). Originally I/O happened via a physically connected system console, but standard streams abstract this. When a command is executed via an interactive shell, the streams are typically connected to the text terminal on which the shell is running, but can be changed with redirection or a pipeline. More generally, a child process inherits the standard streams of its parent process.

In mathematics and computer science, a higher-order function (HOF) is a function that does at least one of the following:

In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.

<span class="mw-page-title-main">Foreach loop</span> Control flow statement for traversing items in a collection

In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.

In computer science, an operator precedence parser is a bottom-up parser that interprets an operator-precedence grammar. For example, most calculators use operator precedence parsers to convert from the human-readable infix notation relying on order of operations to a format that is optimized for evaluation such as Reverse Polish notation (RPN).

In computer programming, an entry point is the place in a program where the execution of a program begins, and where the program has access to command line arguments.

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

A foreign function interface (FFI) is a mechanism by which a program written in one programming language can call routines or make use of services written or compiled in another one. An FFI is often used in contexts where calls are made into a binary dynamic-link library.

In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

This article compares a large number of programming languages by tabulating their data types, their expression, statement, and declaration syntax, and some common operating-system interfaces.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments that follow the POSIX Utility Syntax Guidelines, based on the C interface of getopt.

Getopt is a C library function used to parse command-line options of the Unix/POSIX style. It is a part of the POSIX specification, and is universal to Unix-like systems. It is also the name of a Unix program for parsing command line arguments in shell scripts.

Mustache is a web template system. It is described as a logic-less system because it lacks any explicit control flow statements, like if and else conditionals or for loops; however, both looping and conditional evaluation can be achieved using section tags processing lists and anonymous functions (lambdas). It is named "Mustache" because of heavy use of braces, { }, that resemble a sideways moustache. Mustache is used mainly for mobile and web applications.

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.

In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. It is semantically related to the concept of a coroutine and is often implemented using similar techniques, and is primarily intended to provide opportunities for the program to execute other code while waiting for a long-running, asynchronous task to complete, usually represented by promises or similar data structures. The feature is found in C#, C++, Python, F#, Hack, Julia, Dart, Kotlin, Rust, Nim, JavaScript, and Swift.

<span class="mw-page-title-main">Deno (software)</span> Secure JavaScript and TypeScript runtime

Deno is a runtime for JavaScript, TypeScript, and WebAssembly that is based on the V8 JavaScript engine and the Rust programming language. Deno was co-created by Ryan Dahl, who also created Node.js.

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.