Command-line arguments

From Rosetta Code
Jump to: navigation, search
Command-line arguments
You are encouraged to solve this task according to the task description, using any language you may know.
Command-line arguments is part of Short Circuit's Console Program Basics selection.
Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see Scripted main.

See also Program name.

For parsing command line arguments intelligently, see Parsing command-line arguments.

Example command line:

myprogram -c "alpha beta" -h "gamma"


[edit] Ada

In Ada95 and later versions, command line arguments are available through the predefined package Ada.Command_Line. In Ada83, this would be implementation dependent.

with Ada.Command_line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
procedure Print_Commands is
-- The number of command line arguments is retrieved from the function Argument_Count
-- The actual arguments are retrieved from the function Argument
-- The program name is retrieved from the function Command_Name
Put(Command_Name & " ");
for Arg in 1..Argument_Count loop
Put(Argument(Arg) & " ");
end loop;
end Print_Commands;

[edit] Alternative version using Matreshka

Uses Matreshka

with Ada.Wide_Wide_Text_IO;
with League.Application;
with League.Strings;
procedure Main is
for J in 1 .. League.Application.Arguments.Length loop
(League.Application.Arguments.Element (J).To_Wide_Wide_String);
end loop;
end Main;

[edit] Aikido

The arguments are passed to the program as a vector of strings called args

foreach arg in args {
println ("arg: " + arg)

[edit] Aime

integer i;
i = 0;
while (i < argc()) {
i += 1;

[edit] ALGOL 68

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386 - argc and argv are not part of the standard's prelude
FOR i TO argc DO
printf(($"the argument #"g(-0)" is "gl$, i, argv(i)))

Linux command:

/usr/bin/a68g Command-line_arguments.a68 - 1 2 3 ...


the argument #1 is /usr/bin/a68g
the argument #2 is ./Command-line_arguments.a68
the argument #3 is -
the argument #4 is 1
the argument #5 is 2
the argument #6 is 3
the argument #7 is ...

[edit] AppleScript

#!/usr/bin/env osascript
-- Print first argument
on run argv
return (item 1 of argv)
end run

[edit] AutoHotkey

From the AutoHotkey documentation: "The script sees incoming parameters as the variables %1%, %2%, and so on. In addition, %0% contains the number of parameters passed (0 if none). "

Loop %0% ; number of parameters
params .= %A_Index% . A_Space
If params !=
MsgBox, %0% parameters were passed:`n`n %params%
Run, %A_AhkPath% "%A_ScriptFullPath%" -c "\"alpha beta\"" -h "\"gamma\""

[edit] AWK

#!/usr/bin/awk -f
print "There are " ARGC "command line parameters"
for(l=1; l<ARGC; l++) {
print "Argument " l " is " ARGV[l]

[edit] BASIC

Works with: QuickBASIC

For most older BASICs that supply the keyword COMMAND$, all arguments are returned in a single string that must then be parsed inside the program. (Unlike modern BASICs, there is often no easy way to retrieve the program's name.)

PRINT "args: '"; COMMAND$; "'"

Sample output:

args: 'This is a test.'
Works with: FreeBASIC

FreeBASIC supplies three ways to retrieve the arguments: COMMAND$ (which works identically to QuickBASIC's COMMAND$), COMMAND$() (a string array which works like C's argv[]), and __FB_ARGV__ (an array of pointers which works even more like C's argv[]) and __FB_ARGC__ (which works like C's argc).

PRINT "This program is named "; COMMAND$(0)
i = 1
PRINT "The argument "; i; " is "; COMMAND$(i)
i = i + 1
FOR i = 0 TO __FB_ARGC__ - 1
PRINT "arg "; i; " = '"; *__FB_ARGV__[i]; "'"

Sample output:

C:\>cla 1 2 3
1 2 3
This program is named cla
The argument  1 is 1
The argument  2 is 2
The argument  3 is 3
arg  0 = 'cla'
arg  1 = '1'
arg  2 = '2'
arg  3 = '3'

[edit] Batch File

Works with: Windows NT version 4 or later (includes Windows XP and onward)
@echo off
setlocal enabledelayedexpansion
set Count=0
if not "%1"=="" (
set /a count+=1
set parameter[!count!]=%1
goto loop
for /l %%a in (1,1,%count%) do (
echo !parameter[%%a]!

Another way of doing it

@echo off
setlocal enabledelayedexpansion
set fn=%~f0
set p0=%~0
set p*=%*
set /a c=1
if @%1==@ goto done
set p%c%=%~1
set /a c=c+1
goto loop
set /a c=c-1
set p#=%c%
echo fn=%fn%
echo p0=%p0%
echo p*=%p*%
echo p#=%p#%
for /l %%i in (1,1,%p#%) do (
echo p%%i=!p%%i!


>args2 foo "bar baz" quux
p*=foo "bar baz" quux
p2=bar baz

[edit] BBC BASIC

PRINT @cmd$

[edit] Bracmat

When Bracmat is started with one or more arguments, each argument is evaluated as if it were a Bracmat expression unless an argument (for example the first one) consumes the next argument(s) by calling arg$. Each invocation of arg$ pops one argument from the remaining list of arguments. Calling arg$ when no more arguments are available results in failure. The following program iterates over all arguments following the currently evaluated argument and outputs the argument to standard output.

whl'(arg$:?a&out$(str$("next arg=" !a)))

Now run Bracmat with this program as the first argument in a DOS environment:

bracmat "whl'(arg$:?a&out$(str$(\"next arg=\" !a)))" "a" /b -c 2+3 'd;' "out$(\"13+7=\" 13+7)"

Instead of starting in interactive mode, Bracmat interprets the first argument, which consumes all following arguments. This is output to standard output:

next arg=a
next arg=/b
next arg=-c
next arg=2+3
next arg='d;'
next arg=out$("13+7=" 13+7)

If given an argument index, arg$<arg index> returns the indexed argument without consuming any argument.

bracmat "0:?n&whl'(arg$!n:?a&out$str$(arg[ !n \"]=\" !a)&1+!n:?n)" "a" /b -c 2+3 'd;' "out$(\"13+7=\" 13+7)"


arg[1]=0:?n&whl'(arg$!n:?a&out$str$(arg[ !n "]=" !a)&1+!n:?n)
arg[7]=out$("13+7=" 13+7)
13+7= 20

The last line demonstrates that not only the first argument is evaluated, but also the following arguments.

If Bracmat is run without arguments, Bracmat starts in interactive mode. In that situation calling arg$ fails. The same is true if Bracmat is compiled as a shared library (DLL or so).

[edit] C

Command line arguments are passed to main. Since the program name is also passed as "argument", the provided count is actually one more than the number of program arguments. Traditionally the argument count is named argc and the array of argument strings is called argv, but that's not mandatory; any (non-reserved) name will work just as well. It is, however, a good idea to stick to the conventional names.

Be careful on systems that use Unicode or other multibyte character sets. You may need to use a type of _wchar* and multi-byte-character-set-aware versions of printf.

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[])
int i;
(void) printf("This program is named %s.\n", argv[0]);
for (i = 1; i < argc; ++i)
(void) printf("the argument #%d is %s\n", i, argv[i]);

[edit] C++

Command line arguments are passed the same way as in C.

This example uses iostream. Traditional C I/O also works.

#include <iostream>
int main(int argc, char* argv[])
std::cout << "This program is named " << argv[0] << std::endl;
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
for (int i = 1; i < argc; ++i)
std::cout << "the argument #" << i << " is " << argv[i] << std::endl;
return 0;

[edit] C#

There are at least two methods to access the command-line arguments. The first method is to access the string array passed to Main. This method only accesses the arguments and not the path to the executable.

using System;
namespace RosettaCode {
class Program {
static void Main(string[] args) {
for (int i = 0; i < args.Length; i++)
Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i]));

The second method is to call the Environment.GetCommandLineArgs function. This method also returns the path to the executable as args[0] followed by the actual command line arguments.

using System;
namespace RosettaCode {
class Program {
static void Main() {
string[] args = Environment.GetCommandLineArgs();
for (int i = 0; i < args.Length; i++)
Console.WriteLine(String.Format("Argument {0} is '{1}'", i, args[i]));

[edit] Clean

getCommandLine from the module ArgEnv returns an array of command-line arguments (the first element is the name of the program).

import ArgEnv
Start = getCommandLine

[edit] Clojure

The value of *command-line-args* is a sequence of the supplied command line arguments, or nil if none were supplied.

(dorun (map println *command-line-args*))

[edit] COBOL

The COBOL standard appears to say nothing regarding the retrieval of command-line arguments, although methods of retrieving them are provided by most vendors.

Works with: OpenCOBOL
Works with: Visual COBOL

Getting the arguments in one go, exactly as they were passed in:

PROGRAM-ID. accept-all-args.
01 args PIC X(50).

Getting the arguments one at a time, with arguments being split by whitespace if not in quotes:

PROGRAM-ID. accept-args-one-at-a-time.
01 arg PIC X(50) VALUE SPACES.

[edit] CoffeeScript

Works with: Node.js
console.log arg for arg in process.argv

[edit] Common Lisp

The Common Lisp standard does not specify anything relating to external invocation of a Common Lisp system. The method for getting command-line arguments varies by implementation.

The following function could be used to create a uniform way to access the arguments:

(defun argv ()
#+clisp (ext:argv)
#+sbcl sb-ext:*posix-argv*
#+abcl ext:*command-line-argument-list*
#+clozure (ccl::command-line-arguments)
#+gcl si:*command-args*
#+ecl (loop for i from 0 below (si:argc) collect (si:argv i))
#+cmu extensions:*command-line-strings*
#+allegro (sys:command-line-arguments)
#+lispworks sys:*line-arguments-list*

[edit] D

void main(in string[] args) {
import std.stdio;
foreach (immutable i, arg; args[1 .. $])
writefln("#%2d : %s", i + 1, arg);

[edit] DCL

case is not preserved unless the parameter is in quotes

$ i = 1
$ loop:
$ write sys$output "the value of P''i' is ", p'i
$ i = i + 1
$ if i .le. 8 then $ goto loop
$ @command_line_arguments -c "alpha beta" -h "gamma"
the value of P1 is -C
the value of P2 is alpha beta
the value of P3 is -H
the value of P4 is gamma
the value of P5 is 
the value of P6 is 
the value of P7 is 
the value of P8 is

[edit] Déjà Vu

Command line arguments are found in !args and !opts.

for i range 0 -- len !args:
print\( "Argument #" i " is " )
. get-from !args i
if has !opts :c:
!print "Ah, the -c option."
if has !opts :four:
!. get-from !opts :four
$ vu args-3.deja one two -c three --four=five
Argument #0 is "args-3.deja"
Argument #1 is "one"
Argument #2 is "two"
Argument #3 is "three"
Ah, the -c option.

The order of command line options is lost.

[edit] Delphi

// The program name and the directory it was called from are in
// param[0] , so given the axample of myprogram -c "alpha beta" -h "gamma"
for x := 0 to paramcount do
writeln('param[',x,'] = ',param[x]);
// will yield ( assuming windows and the c drive as the only drive) :
// param[0] = c:\myprogram
// param[1] = -c
// param[2] = alpha beta
// param[3] = -h
// param[4] = gamma

[edit] E


[edit] Eiffel

This class inherits functionality for dealing with command line arguments from class ARGUMENTS. It uses the feature separate_character_option_value to return the values by option name for each of the two arguments.

feature {NONE} -- Initialization
-- Print values for arguments with options 'c' and 'h'.
print ("Command line argument value for option 'c' is: ")
print (separate_character_option_value ('c') + "%N")
print ("Command line argument value for option 'h' is: ")
print (separate_character_option_value ('h') + "%N")
io.read_line -- Keep console window open

Output (for command line arguments: -c "alpha beta" -h "gamma"):

Command line argument value for option 'c' is: alpha beta
Command line argument value for option 'h' is: gamma

[edit] Emacs Lisp

#!/usr/bin/env emacs --script
(dolist (arg command-line-args-left) (message arg))

[edit] Erlang

When used as a script language the arguments is a list to the main/1 function. When compiled use init:get_arguments/0

3> init:get_arguments().


{c,["alpha beta"]},

init:get_argument(name) can be used to fetch value of a particular flag

4> init:get_argument(h).
5> init:get_argument(c).
{ok,[["alpha beta"]]}

[edit] Euphoria

constant cmd = command_line()
printf(1,"Interpreter/executable name: %s\n",{cmd[1]})
printf(1,"Program file name: %s\n",{cmd[2]})
if length(cmd)>2 then
puts(1,"Command line arguments:\n")
for i = 3 to length(cmd) do
printf(1,"#%d : %s\n",{i,cmd[i]})
end for
end if

[edit] F#

The entry-point function accepts the comment line arguments as an array of strings. The following program will print each argument on a separate line.

let main args =
Array.iter (fun x -> printfn "%s" x) args

[edit] Factor

USING: io sequences command-line ;
(command-line) [ print ] each

[edit] Fancy

ARGV each: |a| {
a println # print each given command line argument

[edit] Fantom

class Main
public static Void main (Str[] args)
echo ("command-line args are: " + args)

[edit] Forth

Access to command line arguments is not a standard feature of Forth, since it is designed to be used without an operating system. The popular GNU implementation gforth runs from a shell and can access command line arguments similar to C: variable argc contains the count (including the command itself) and arg is a function that returns the nth argument as a string.

Works with: gforth version 0.6.2
\ args.f: print each command line argument on a separate line
: main
argc @ 0 do i arg type cr loop ;
main bye

Here is output from a sample run.

$ gforth args.f alpha "beta gamma" delta
beta gamma

[edit] Fortran

Works with: Fortran version 2003 and later
program command_line_arguments
implicit none
integer, parameter :: len_max = 256
integer :: i , nargs
character (len_max) :: arg
nargs = command_argument_count()
!nargs = iargc()
do i = 0, nargs
call get_command_argument (i, arg)
!call getarg (i, arg)
write (*, '(a)') trim (arg)
end do
end program command_line_arguments

Note: This sample uses the Fortran 2003 intrinsic routines command_argument_count and get_command_argument instead of the nonstandard extensions iargc and getarg. Most Fortran compilers support both.

Sample usage:

> ./a.out -c "alpha beta" -h "gamma"
alpha beta

[edit] Frink

Arguments to a program are available in the ARGS array variable.


[edit] FunL

println( args )

[edit] Gambas

DIM l AS Integer
DIM numparms AS Integer
DIM parm AS String
numparms = Application.Args.Count
FOR l = 0 TO numparms - 1
parm = Application.Args[l]
PRINT l; " : "; parm

[edit] Go

package main
import (
func main() {
for i, x := range os.Args {
if i == 0 {
fmt.Printf("This program is named %s.\n", x)
} else {
fmt.Printf("the argument #%d is %s\n", i, x)

[edit] Groovy

Command-line arguments are accessible via the args list variable. The following is saved as the file "Echo.groovy":

println args

The existence of command-line arguments presupposes the existence of a command line interpreter. The following test runs were entered in a cygwin bash shell in a Microsoft Windows XP system:

$ groovy Echo this is an argument list
[this, is, an, argument, list]
$ groovy Echo -x alkfrew4oij -cdkjei +22
[-x, alkfrew4oij, -cdkjei, +22]

For more sophisticated command-line option and option-argument parsing use the CliBuilder (command-line interface builder) library, which extends the functionality of the Java-based Apache Commons CLI library to Groovy.

[edit] Harbour

Uses the Harbour-specific hb_PValue() function

FOR i := 1 TO PCount()
? "argument", hb_ntos( i ), "=", hb_PValue( i )

[edit] Haskell

Defined by the System module, getArgs :: IO [String] provides the command-line arguments in a list.


import System
main = getArgs >>= print
myprog a -h b c
=> ["a","-h","b","c"]

[edit] HicEst

DO i = 2, 100 ! 1 is HicEst.exe
EDIT(Text=$CMD_LINE, SePaRators='-"', ITeM=i, IF ' ', EXit, ENDIF, Parse=cmd, GetPosition=position)
IF(position > 0) WRITE(Messagebox) cmd

[edit] Icon and Unicon

Command line parameters are passed to Icon/Unicon programs as a list of strings.

procedure main(arglist)
every write(!arglist)
includes options that parses the command line as switches and arguments and returns the results in a table.

[edit] Io

System args foreach(a, a println)

[edit] Ioke

System programArguments each(println)

[edit] J

The global ARGV holds the command line arguments. Thus, a program to display them:


[edit] Java

public class Arguments {
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
for(int i = 0; i < args.length; i++)
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);

For more sophisticated command-line option and option-argument parsing use the Apache Commons CLI (command-line interface) library.

[edit] JavaScript

Works with: JScript
var objArgs = WScript.Arguments;
for (var i = 0; i < objArgs.length; i++)
import System;
var argv:String[] = Environment.GetCommandLineArgs();
for (var i in argv)
Works with: Rhino
Works with: SpiderMonkey
for (var i = 0; i < arguments.length; i++)

[edit] Julia

prog = basename(Base.source_path())
println(prog, "'s command-line arguments are:")
for s in ARGS
println(" ", s)
$ julia command_line_arguments.jl -c "alpha beta" -h "gamma"
command_line_arguments.jl's command-line arguments are:
    alpha beta

[edit] Lasso

iterate($argv) => {
stdoutnl("Argument " + loop_count + ": " + loop_value)


$ lasso9 arguments.lasso -c "alpha beta" -h "gamma"
Argument 1: arguments.lasso
Argument 2: -c
Argument 3: alpha beta
Argument 4: -h
Argument 5: gamma

[edit] LFE

To demonstrate this, we can start the LFE REPL up with the parameters for this example:

$ ./bin/lfe -pa ebin/ -c "alpha beta" -h "gamma"

Once we're in the shell, we can get all the initializing arguments with this call:

> (: init get_arguments)
(#(root ("/opt/erlang/r15b03"))
#(progname ("erl"))
#(home ("/Users/oubiwann"))
#(user ("lfe_boot"))
#(pa ("ebin/"))
#(c ("alpha beta"))
#(h ("gamma")))

We can also get specific arguments if we know their keys:

> (: init get_argument 'c)
#(ok (("alpha beta")))
> (: init get_argument 'h)
#(ok (("gamma")))

[edit] Liberty BASIC

print CommandLine$


Works with: UCB Logo version 5.6

If the command line to a logo script is written

logo file.logo - arg1 arg2 arg3

Then the arguments after the "-" are found in a list in variable :COMMAND.LINE

[arg1 arg2 arg3]

Alternatively, make the first line of an executable logo script:

#! /usr/bin/logo -

to be able to invoke the script with arguments.

file.logo arg1 arg2 arg3

[edit] LSE64

argc , nl  # number of arguments (including command itself)
0 # argument
dup arg dup 0 = || ,t 1 + repeat

[edit] Lua

The lua scripting language does not use argc and argv conventions for the command line parameters. Instead, the command line parameters to the main script are provided through the global table arg. The script name is placed into element zero of arg, and the script parameters go into the subsequent elements:

print( "Program name:", arg[0] )
print "Arguments:"
for i = 1, #arg do
print( i," ", arg[i] )

[edit] Mathematica


#!/usr/local/bin/MathematicaScript -script


{myprogram,-c,alpha beta,-h,gamma}

[edit] Mercury

:- module cmd_line_args.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, string.
main(!IO) :-
io.progname("", ProgName, !IO),
io.format("This program is named %s.\n", [s(ProgName)], !IO),
io.command_line_arguments(Args, !IO),
list.foldl2(print_arg, Args, 1, _, !IO).
:- pred print_arg(string::in, int::in, int::out, io::di, io::uo) is det.
print_arg(Arg, ArgNum, ArgNum + 1, !IO) :-
io.format("the argument #%d is %s\n", [i(ArgNum), s(Arg)], !IO).

[edit] MMIX

argv   IS    $1
argc IS $0
i IS $2
LOC #100
Main LOC @
SETL i,1 % i = 1
Loop CMP $3,argc,2 % argc < 2 ?
BN $3,1F % then jump to end
XOR $255,$255,$255 % clear $255
8ADDU $255,i,argv % i*8 + argv
LDOU $255,$255,0 % argv[i]
TRAP 0,Fputs,StdOut % write the argument
GETA $255,NewLine % add a newline
TRAP 0,Fputs,StdOut
INCL i,1 % increment index
SUB argc,argc,1 % argc--
BP argc,Loop % argc > 0? then Loop
1H LOC @
XOR $255,$255,$255 % exit(0)
TRAP 0,Halt,0
NewLine BYTE #a,0

[edit] Modula-2

FROM Arguments IMPORT GetArgs, ArgTable, GetEnv;
FROM InOut IMPORT WriteCard, WriteLn, WriteString;
VAR count, item : SHORTCARD;
storage : ArgTable;
GetArgs (count, storage);
WriteString ('Count ='); WriteCard (count, 4); WriteLn;
item := 0;
WriteCard (item, 4);
WriteString (' : ');
WriteString (storage^ [item]^);
INC (item)
UNTIL item = count
END try.


jan@Beryllium:~/modula/test$ try jantje zag eens pruimen hangen
Count = 6
0 : try
1 : jantje
2 : zag
3 : eens
4 : pruimen
5 : hangen

[edit] Modula-3

Command line parameters are accessed using the Params module.

IMPORT IO, Params;
IO.Put(Params.Get(0) & "\n");
IF Params.Count > 1 THEN
FOR i := 1 TO Params.Count - 1 DO
IO.Put(Params.Get(i) & "\n");
END Args.


martin@thinkpad:~$ ./prog
martin@thinkpad:~$ ./prog 10
martin@thinkpad:~$ ./prog 10 20

[edit] Nemerle

using System;
using System.Console;
module CLArgs
Main(args : array[string]) : void
foreach (arg in args) Write($"$arg "); // using the array passed to Main(), everything after the program name
def cl_args = Environment.GetCommandLineArgs(); // also gets program name
foreach (cl_arg in cl_args) Write($"$cl_arg ");

[edit] NetRexx

In a stand-alone application NetRexx places the command string passed to it in a variable called arg.

/* NetRexx */
-- sample arguments: -c "alpha beta" -h "gamma"
say "program arguments:" arg


program arguments: -c "alpha beta" -h "gamma"

[edit] Nim

import os
let programName = paramStr(0)
let arguments = commandLineParams()

[edit] Oberon-2

Works with: oo2c
MODULE CommandLineArguments;
Out := NPCT:Console;
Out.String("Args number: ");Out.Int(Args.Number(),0);Out.Ln;
Out.String("0.- : ");Out.String(Args.AsString(0));Out.Ln;
Out.String("1.- : ");Out.String(Args.AsString(1));Out.Ln;
Out.String("2.- : ");Out.String(Args.AsString(2));Out.Ln;
Out.String("3.- : ");Out.String(Args.AsString(3));Out.Ln;
Out.String("4.-: ");Out.String(Args.AsString(4));Out.Ln
END CommandLineArguments.
Args number: 5
0.- : bin/CommandLineArguments
1.- : -c
2.- : alpha beta
3.- : -h
4.-: gamma

[edit] Objeck

bundle Default {
class Line {
function : Main(args : String[]) ~ Nil {
each(i : args) {

[edit] Objective-C

In addition to the regular C mechanism of arguments to main(), Objective-C also has another way to get the arguments as string objects inside an array object:

NSArray *args = [[NSProcessInfo processInfo] arguments];
NSLog(@"This program is named %@.", [args objectAtIndex:0]);
NSLog(@"There are %d arguments.", [args count] - 1);
for (i = 1; i < [args count]; ++i){
NSLog(@"the argument #%d is %@", i, [args objectAtIndex:i]);

[edit] OCaml

The program name is also passed as "argument", so the array length is actually one more than the number of program arguments.

let () =
Printf.printf "This program is named %s.\n" Sys.argv.(0);
for i = 1 to Array.length Sys.argv - 1 do
Printf.printf "the argument #%d is %s\n" i Sys.argv.(i)

[edit] Using the Arg module

(* default values *)
let somebool = ref false
let somestr = ref ""
let someint = ref 0
let usage = "usage: " ^ Sys.argv.(0) ^ " [-b] [-s string] [-d int]"
let speclist = [
("-b", Arg.Set somebool, ": set somebool to true");
("-s", Arg.Set_string somestr, ": what follows -s sets some string");
("-d", Arg.Set_int someint, ": some int parameter");
let () =
(* Read the arguments *)
(fun x -> raise (Arg.Bad ("Bad argument : " ^ x)))
Printf.printf " %b %d '%s'\n" !somebool !someint !somestr;

% ocaml --help
usage: [-b] [-s string] [-d int]
  -b : set somebool to true
  -s : what follows -s sets some string
  -d : some int parameter
  --help  Display this list of options

% ocaml -d 4 -b -s blabla
 true 4 'blabla'

% ocaml
 false 0 ''

[edit] Oforth

System.Args returns command line arguments.

All arguments that begin with "--" are not included into this list. The first argument is the program name, so this list is never empty.

System.Args println

[edit] Oz

[edit] Raw arguments

Like in C, but without the program name:

import Application System
ArgList = {Application.getArgs plain}
{ForAll ArgList System.showInfo}
{Application.exit 0}

[edit] Preprocessed arguments

import Application System
ArgSpec =
c(type:string single %% option "--c" expects a string, may only occur once,
optional:false char:&c) %% is not optional and has a shortcut "-c"
h(type:string single %% option "--h" expects a string, may only occur once,
default:"default h" %% is optional and has a default value if not given
char:&h) %% and has a shortcut "-h"
Args = {Application.getArgs ArgSpec}
{System.showInfo Args.c}
{System.showInfo Args.h}
{Application.exit 0}

[edit] Pascal

Depends on implementation.

[edit] Perl

Works with: Perl version 5.x

@ARGV is the array containing all command line parameters

my @params = @ARGV;
my $params_size = @ARGV;
my $second = $ARGV[1];
my $fifth = $ARGV[4];

If you don't mind importing a module:

use Getopt::Long;
GetOptions (
'help|h' => \my $help,
'verbose|v' => \my $verbose,

[edit] Perl 6

Perl 5's @ARGV is available as @*ARGS. Alternatively, if you define a subroutine named MAIN, Perl will automatically process @*ARGS according to Unix conventions and MAIN's signature (or signatures, if your MAIN is a multi sub) and then call MAIN with appropriate arguments; see Synopsis 6 or [1].

# with arguments supplied
$ perl6 -e 'sub MAIN($x, $y) { say $x + $y }' 3 5
# missing argument:
$ perl6 -e 'sub MAIN($x, $y) { say $x + $y }' 3
-e '...' x y

If the program is stored in a file, the file name is printed instead of -e '...'.

[edit] Phix

constant cmd = command_line()
if cmd[1]=cmd[2] then
printf(1,"Compiled executable name: %s\n",{cmd[1]})
printf(1,"Interpreted (using %s) source name: %s\n",cmd[1..2])
end if
if length(cmd)>2 then
puts(1,"Command line arguments:\n")
for i = 3 to length(cmd) do
printf(1,"#%d : %s\n",{i,cmd[i]})
end for
end if

When interpreting, the first two elements returned by command_line() are {interpreter,source}.
When compiled, the first two elements are instead {executable,executable}, so the parameters (if any) are consistently the 3rd element onwards.

C:\Program Files (x86)\Phix>p testcl -c "alpha beta" -h "gamma"
{"C:\\Program Files (x86)\\Phix\\p.exe","C:\\Program Files (x86)\\Phix\\testcl.exw","-c","alpha beta","-h","gamma"}
Interpreted (using C:\Program Files (x86)\Phix\p.exe) source name: C:\Program Files (x86)\Phix\testcl.exw
Command line arguments:
#3 : -c
#4 : alpha beta
#5 : -h
#6 : gamma
C:\Program Files (x86)\Phix>p -c testcl -c "alpha beta" -h "gamma"
{"C:\\Program Files (x86)\\Phix\\testcl.exe","C:\\Program Files (x86)\\Phix\\testcl.exe","-c","alpha beta","-h","gamma"}
Compiled executable name: C:\Program Files (x86)\Phix\testcl.exe
Command line arguments:
#3 : -c
#4 : alpha beta
#5 : -h
#6 : gamma
C:\Program Files (x86)\Phix>testcl -c "alpha beta" -h "gamma"
{"C:\\Program Files (x86)\\Phix\\testcl.exe","C:\\Program Files (x86)\\Phix\\testcl.exe","-c","alpha beta","-h","gamma"}
Compiled executable name: C:\Program Files (x86)\Phix\testcl.exe
Command line arguments:
#3 : -c
#4 : alpha beta
#5 : -h
#6 : gamma
C:\Program Files (x86)\Phix>

[edit] PHP

When PHP is run from the command line, the special variables $argv and $argc contain the array of arguments, and the number of arguments, respectively. The program name is passed as the first argument.

$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);

[edit] PicoLisp

There are three ways to handle command-line arguments in PicoLisp:

1. Obtain all arguments as a list of strings via 'argv'

2. Fetch each argument individually with 'opt'

3. Use the built-in command-line interpretation, where arguments starting with a hyphen are executed as functions.

Here we use the third option, as it is not so obvious, sometimes more flexible, and in fact the most commonly used one for application development.

We define 'c' and 'h' as functions, which retrieve their argument with 'opt', and then 'load' all remaining command line arguments.

#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(de c ()
(prinl "Got 'c': " (opt)) )
(de h ()
(prinl "Got 'h': " (opt)) )
(load T)


$ ./myprogram -c "alpha beta" -h "gamma"
Got 'c': alpha beta
Got 'h': gamma

[edit] PL/I

/* The entire command line except the command word itself is passed */
/* to the parameter variable in PL/I. */
program: procedure (command_line) options (main);
declare command_line character (100) varying;
end program;

[edit] Pop11

variable poparglist contains list of command line arguments (as strings). One can use iteration over list to process then (for example print).

lvars arg;
for arg in poparglist do
printf(arg, '->%s<-\n');

[edit] PowerBASIC

For versions of PowerBASIC prior to PB/Win 9 and PB/CC 5, the only option available is identical to the one used by QuickBASIC above:

? "args: '"; COMMAND$; "'"

Current versions of PowerBASIC (with the likely exception of PB/DOS) include COMMAND$() that works similarly to FreeBASIC's COMMAND$(), except that you can't retrieve the application's name:

'these two both return ALL args
PRINT "The argument "; i; " is "; COMMAND$(i)
i = i + 1

[edit] PowerShell

In PowerShell the arguments to a script can be accessed with the $args array:

$i = 0
foreach ($s in $args) {
Write-Host Argument (++$i) is $s

[edit] Pure

Arguments are in global variables, argc and argv.

using system;
printf "There are %d command line argumants\n" argc;
puts "They are " $$ map (puts) argv;

[edit] PureBasic

[edit] Reading all parameters

You can easily read all parameters by using ProgramParameter() without argument.

If OpenConsole()
Define n=CountProgramParameters()
PrintN("Reading all parameters")
While n
Print(#CRLF$+"Press Enter")

[edit] Reading specific parameters

You can specify which parameter 'n' to read.

If OpenConsole()
Define n
PrintN("Reading specific pameters")
For n=0 To CountProgramParameters()
Print(#CRLF$+"Press Enter")

[edit] Python

sys.argv is a list containing all command line arguments, including the program name. Typically you slice the list to access the actual command line argument:

import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

When running a module by invoking Python, the Python interpreter processes and removes some of the arguments, and the module cannot access them. To process command line arguments, run the module directly. sys.argv is a copy of the command line arguments; modifying sys.argv will not change the arguments seen by other processes, e.g. ps. (In other words sys.argv is an object which contains a copy of the process' command line arguments ... modifying that copy is only visible from within the Python program and not externally).

For powerful option parsing capabilities check out the optparse module.

[edit] R

Following adapted from this post by Forester:

Suppose you want to call your script test.r with the arguments a=1 b=c(2,5,6), where b is a numeric vector. Suppose you also want to redirect your output to test.out (not that you have a choice--I still don't know how to make R send shell-script output to stdout). You would then run

R CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out

from the commandline, with the following text in test.r:

# Read the commandline arguments
args <- (commandArgs(TRUE))
# args is now a list of character vectors
# First check to see if any arguments were passed,
# then evaluate each argument.
if (length(args)==0) {
print("No arguments supplied.")
# Supply default values
a <- 1
b <- c(1,1,1)
} else {
for (i in 1:length(args)) {

(possibly preceding code that actually does something :-) Your output test.out would then contain (e.g., if you cat it)

[1] 2
[1]  6 15 18
> proc.time()
   user  system elapsed 
  0.168   0.026   0.178 

If you know how to get the output

  • sent to stdout (i.e., as is normal with shell scripts)
  • done without the profiling

please update this example!

[edit] Racket

The following is the simplest program that prints the command-line arguments:

#lang racket

You can also explicitly print each argument to standard output:

#lang racket
(for ([arg (current-command-line-arguments)]) (displayln arg))

[edit] RapidQ

PRINT "This program is named "; Command$(0)
FOR i=1 TO CommandCount
PRINT "The argument "; i; " is "; Command$(i)

[edit] Raven

ARGS print
stack (6 items)
0 => "raven"
1 => "myprogram"
2 => "-c"
3 => "alpha beta"
4 => "-h"
5 => "gamma"

[edit] REALbasic

Function Run(args() as String) As Integer
For each arg As String In args
End Function

Output (given arguments: --foo !bar "bat bang"):

bat bang

[edit] REXX

The entire command line is passed by REXX to the program.

say 'command arguments:'
say arg(1)


myprogram -c "alpha beta" -b "gamma"

However, the the example shown, it's suggestted that (maybe) only options that start with a minus (-) are to be examined and assumed to be options.

parse arg aaa                          /*get the arguments.        */
/*another version: */
/* aaa=arg(1) */
say 'command arguments:'
say aaa
opts='' /*placeholder for options. */
data='' /*placeholder for data. */
do j=1 to words(aaa)
if left(x,1)=='-' then opts=opts x /*Option? Then add to opts.*/
else data=data x /*Must be data. Add to data.*/
/*the above process adds a leading blank to OPTS and DATA*/
opts=strip(opts,'L') /*strip leading blanks. */
data=strip(data,'l') /*strip leading blanks. */
say 'options='opts
say ' data='data

[edit] Notes to users of Microsoft Windows

Note that some REXX pass the command line as is, but Regina REXX lets the operating system parse it first (for instance Windows), and Windows will pass anything in inside double quotes (") to the program as is. Any other data not in double quotes is passed as is.

Output from Regina REXX under Windows with the invocation:

myprogram -c "alpha beta" -h "gamma"
command arguments:
-c alpha beta -h gamma

options=-c -h
   data=alpha beta gamma

Output from others REXXes under Windows with the invocation:

myprogram -c "alpha beta" -h "gamma"
command arguments:
-c "alpha beta" -h "gamma"

options=-c -h
   data="alpha beta" "gamma"

[edit] Notes to Unix users

The rexx programming language does not preserve command line parameters containing spaces. This renders it unsuitable for use for wrapperscript applications, where filenames containing spaces need to be preserved, because there is no way to differentiate between a space within a parameter, and a space used to separate parameters.

[edit] Scenario

If a script is called as follows:

ccwrapper "foo bar.c" "bar bar.c"

From the shell:

argv[0] = ccwrapper
argv[1] = foo bar.c
argv[2] = bar bar.c

It is a requirement of a wrapper that !argv[1] and !argv[2] are preserved when passed to the target application (a C compiler, in this example). Current implementations of rexx treat the command line arguments as one long argument:

arg() = 1
arg(1) = "foo bar.c bar bar.c"

The [parser] would separates the command line arguments by spaces. this results in !argv[1] and !argv[2] becoming split, so the target application would be called with different arguments:

argv[1] = foo
argv[2] = bar.c
argv[3] = bar
argv[4] = bar.c

This has a different meaning to the compiler, so the arguments forwarded from rexx are rendered useless.

[edit] Workaround

A workaround would be to create a wrapper around the rexx interpreter that encodes the commandline before calling rexx. The rexx application then decodes it. Some rexx interpreters, such as regina also provide a !-a switch as a workaround.

[edit] Ruby

Command line arguments are available in the constant Object::ARGV.


#! /usr/bin/env ruby
 myprog a -h b c
 => ["a","-h","b","c"]

[edit] Rust

use std::env;
fn main(){
let args: Vec<_> = env::args().collect();
println!("{:?}", args);


./program -c "alpha beta" -h "gamma"
["./program", "-c", "alpha beta", "-h", "gamma"]

[edit] Sather

class MAIN is
main(args:ARRAY{STR}) is
#OUT + args.elt! + "\n";

As in C (and others), the first element is the command itself (exactly as it is written in the command line and after shell variable expansion); e.g.

$ /home/home/rosetta/sather/a.out arg1 arg2 arg3



[edit] Scala

Library: Scala

Calling Scala from command line means invoking a method called main, defined on an object, whose type is (Array[String]):Unit, meaning it receives an array of strings, and returns unit. That array contains the command line arguments.

object CommandLineArguments extends App { 
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}")

When running a Scala script, where the whole body is executed, the arguments get stored in an array of strings called argv:

println(s"Received the following arguments: + ${argv.mkString("", ", ", ".")}")

[edit] Scheme

 (define (main args)
(for-each (lambda (arg) (display arg) (newline)) args))

[edit] Seed7

$ include "seed7_05.s7i";
const proc: main is func
var integer: i is 0;
writeln("This program is named " <& name(PROGRAM) <& ".");
for i range 1 to length(argv(PROGRAM)) do
writeln("The argument #" <& i <& " is " <& argv(PROGRAM)[i]);
end for;
end func;

[edit] Sidef

Command line arguments are available in the ARGV array.

say ARGV;
% myprog -c "alpha beta" -h "gamma"
['-c', 'alpha beta', '-h', 'gamma']

[edit] Slate

StartupArguments do: [| :arg | inform: arg]

[edit] Smalltalk

Works with: GNU Smalltalk
(1 to: Smalltalk getArgc) do: [ :i |
(Smalltalk getArgv: i) displayNl
Works with: Smalltalk/X
Smalltalk commandLineArguments printCR

[edit] Standard ML

print ("This program is named " ^ () ^ ".\n");
val args = CommandLine.arguments ();
(fn (i, x) => print ("the argument #" ^ Int.toString (i+1) ^ " is " ^ x ^ "\n"))
(Array.fromList args);

[edit] Swift

let args = Process.arguments
println("This program is named \(args[0]).")
println("There are \(args.count-1) arguments.")
for i in 1..<args.count {
println("the argument #\(i) is \(args[i])")


Works with: Swift version 1.2+
println("This program is named \(String.fromCString(Process.unsafeArgv[0])!).")
println("There are \(Process.argc-1) arguments.")
for i in 1 ..< Int(Process.argc) {
println("the argument #\(i) is \(String.fromCString(Process.unsafeArgv[i])!)")
Works with: Swift version 1.0-1.1
println("This program is named \(String.fromCString(C_ARGV[0])!).")
println("There are \(C_ARGC-1) arguments.")
for i in 1 ..< Int(C_ARGC) {
println("the argument #\(i) is \(String.fromCString(C_ARGV[i])!)")

[edit] Tcl

The predefined global variable argc contains the number of arguments passed to the program after the script being executed, argv contains those arguments as a list. (The name of the script is in the argv0 global variable, and the name of the executable interpreter itself is returned by the command info nameofexecutable.) Retrieving the second argument might look something like this:

if { $argc > 1 } {
puts [lindex $argv 1]

(Tcl counts from zero, thus [lindex $list 1] retrieves the second item in the list)

[edit] Toka

Arguments are stored into an array. The first element in the array is the name of the program, the rest are the arguments in order. The number of arguments is provided by #args.

[ arglist array.get type cr ] is show-arg
[ dup . char: = emit space ] is #=
1 #args [ i #= show-arg ] countedLoop

[edit] TXR

Command line arguments in TXR's pattern-based extraction language can be treated as the lines of a text stream, which is arranged using the directive @(next :args). Thus TXR's text parsing capabilities work over the argument list.

This @(next :args) should be written as the first line of the TXR program, because TXR otherwise interprets the first argument as the name of an input file to open.

@(next :args)
My args are: {@(rep)@arg, @(last)@arg@(end)}
$ ./txr args.txr
My args are: {}
$ ./txr args.txr 1
My args are: {1}
$ ./txr args.txr 1 2 3
My args are: {1, 2, 3}

Arguments are also available via two predefined variables: *full-args* and *args*, which are lists of strings, such that *args* is a suffic of *full-args*. *full-args* includes the arguments that were processed by TXR itself; *args* omits them.

Here is an example program which requires exactly three arguments. Note how ldiff is used to compute the arguments that are processed by TXR (the interpreter name, any special arguments and script name), to print an accurate usage message.

(tree-case *args*
((a b c) (put-line "got three args, thanks!"))
(else (put-line `usage: @(ldiff *full-args* *args*) <arg1> <arg2> <arg3>`)))
$ txr command-line-args.txr 1 2
usage: txr command-line-args.txr <arg1> <arg2> <arg3>
$ txr command-line-args.txr 1 2 3 4
usage: txr command-line-args.txr <arg1> <arg2> <arg3>
$ txr command-line-args.txr 1 2 3
got three args, thanks!

[edit] UNIX Shell

[edit] Bourne Shell

To retrieve the entire list of arguments:


To retrieve the second and fifth arguments:


[edit] Ursala

Command line arguments are accessible to an application through a data structure initialized by the run-time system. This example application does nothing but display the data structure on standard output.

#import std
#executable ('parameterized','')
clarg = <.file$[contents: --<''>+ _option%LP]>+ ~command.options

Here is a bash terminal session.

$ clarg -c alpha,beta -h gamma --foo=bar,baz
      keyword: 'c',
      parameters: <'alpha','beta'>],
      position: 1,
      keyword: 'h',
      parameters: <'gamma'>],
      position: 2,
      longform: true,
      keyword: 'foo',
      parameters: <'bar','baz'>]>

[edit] V

The arguments to the program are stored in the stack,


$stack puts
./args.v a b c
=[args.v a b c]

[edit] Visual Basic

Like Qbasic, Visual Basic returns all of the args in the built-in variable Command$:

Sub Main
MsgBox Command$
End Sub

[edit] Visual Basic .NET

This syntax will tokenize the command line arguments. Tokens are normally delimited by spaces, but spaces can be part of a token if surrounded by quotes.

Sub Main(ByVal args As String())
For Each token In args
End Sub

[edit] zkl

File myprogram.zkl:


zkl myprogram -c "alpha beta" -h "gamma"

L("/home/craigd/Projects/ZKL/Bin/zkl","myprogram","-c","alpha beta","-h","gamma")
L("-c","alpha beta","-h","gamma")
Personal tools