Command-line arguments: Difference between revisions
No edit summary |
|||
(73 intermediate revisions by 41 users not shown) | |||
Line 11: | Line 11: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
<code>:argv</code> is a list containing all command line arguments, including the program name. |
<code>:argv</code> is a list containing all command line arguments, including the program name. |
||
< |
<syntaxhighlight lang="11l">:start: |
||
print(‘Program name: ’:argv[0]) |
print(‘Program name: ’:argv[0]) |
||
print("Arguments:\n":argv[1..].join("\n"))</ |
print("Arguments:\n":argv[1..].join("\n"))</syntaxhighlight> |
||
=={{header|8080 Assembly}}== |
|||
This program runs under CP/M. CP/M includes some very rudimentary argument parsing: it assumes that the |
|||
first two space-separated arguments are filenames. Apart from that you can get the raw command line, except |
|||
that all lowercase letters are made uppercase. |
|||
If you need any further parsing, the program needs to do that by itself, which led to many people not bothering. |
|||
(The CP/M assembler in particular is infamous for abusing the file extension to take arguments.) The following program shows |
|||
everything CP/M gives it. |
|||
<syntaxhighlight lang="8080asm">putch: equ 2 ; CP/M syscall to print character |
|||
puts: equ 9 ; CP/M syscall to print $-terminated string |
|||
arglen: equ 80h ; Length of argument |
|||
argmt: equ 81h ; Argument string |
|||
fcb1: equ 5Ch ; FCBs |
|||
fcb2: equ 6Ch |
|||
org 100h |
|||
;;; Print all argument(s) as given |
|||
lxi d,cmdln ; Print 'Command line: ' |
|||
mvi c,puts |
|||
call 5 |
|||
lda arglen ; Retrieve the length of the argument |
|||
lxi h,argmt ; Pointer to argument string |
|||
call plstr |
|||
;;; CP/M also assumes that the first two words on the command |
|||
;;; line are filenames, and prepares two FCBs with the filenames |
|||
;;; in them. If there are no filenames, they will be blank. |
|||
lxi d,file1 ; Print the first one |
|||
mvi c,puts |
|||
call 5 |
|||
mvi a,11 ; Filenames are 8+3 characters long and padded with |
|||
lxi h,fcb1+1 ; spaces |
|||
call plstr |
|||
lxi d,file2 ; Print the second one |
|||
mvi c,puts |
|||
call 5 |
|||
mvi a,11 |
|||
lxi h,fcb2+1 |
|||
; ... fall through - on small systems saving bytes is a virtue |
|||
;;; This subroutine prints a length-A string in HL. |
|||
plstr: ana a ; If A=0, print nothing. |
|||
rz |
|||
push psw ; Save A and HL registers on the stack |
|||
push h ; (CP/M syscalls clobber all registers) |
|||
mov e,m ; Print character under HL |
|||
mvi c,putch |
|||
call 5 |
|||
pop h ; Restore A and HL registers |
|||
pop psw |
|||
inx h ; Increment string pointer |
|||
dcr a ; Decrement character counter |
|||
jnz plstr ; Print next character if not zero |
|||
ret |
|||
cmdln: db 'Command line: $' |
|||
file1: db 13,10,'File 1: $' |
|||
file2: db 13,10,'File 2: $'</syntaxhighlight> |
|||
{{out}} |
|||
<pre>A>args |
|||
A>args |
|||
Command line: |
|||
File 1: |
|||
File 2: |
|||
A>args -c "alpha beta" -h "gamma" |
|||
Command line: -C "ALPHA BETA" -H "GAMMA" |
|||
File 1: -C |
|||
File 2: "ALPHA |
|||
A>args foobar.baz barbaz.qux |
|||
Command line: FOOBAR.BAZ BARBAZ.QUX |
|||
File 1: FOOBAR BAZ |
|||
File 2: BARBAZ QUX |
|||
</pre> |
|||
=={{header|8086 Assembly}}== |
|||
The method for doing this depends on the memory model of your program. For a COM file, everything is contained in one segment, including the command line arguments. The program starts at offset 100h and the command line arguments start at 81h. It's as simple as reading from that memory address. |
|||
For an EXE file, both the <code>DS</code> and <code>ES</code> registers are set to the program segment prefix as soon as the program begins. You'll need to load from offset 81h to FFh to get the command line arguments. |
|||
=={{header|AArch64 Assembly}}== |
|||
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }} |
|||
<syntaxhighlight lang AArch64 Assembly> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
|||
/* program commandLine64.s */ |
|||
/************************************/ |
|||
/* Constantes */ |
|||
/************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeConstantesARM64.inc" |
|||
/************************************/ |
|||
/* Initialized data */ |
|||
/************************************/ |
|||
.data |
|||
szCarriageReturn: .asciz "\n" |
|||
/************************************/ |
|||
/* UnInitialized data */ |
|||
/************************************/ |
|||
.bss |
|||
.align 4 |
|||
/************************************/ |
|||
/* code section */ |
|||
/************************************/ |
|||
.text |
|||
.global main |
|||
main: // entry of program |
|||
mov fp,sp // fp <- start address |
|||
ldr x4,[fp] // number of Command line arguments |
|||
add x5,fp,#8 // first parameter address |
|||
mov x2,#0 // init loop counter |
|||
1: |
|||
ldr x0,[x5,x2,lsl #3] // string address parameter |
|||
bl affichageMess // display string |
|||
ldr x0,qAdrszCarriageReturn |
|||
bl affichageMess // display carriage return |
|||
add x2,x2,#1 // increment counter |
|||
cmp x2,x4 // number parameters ? |
|||
blt 1b // loop |
|||
100: // standard end of the program |
|||
mov x0, #0 // return code |
|||
mov x8,EXIT |
|||
svc 0 // perform the system call |
|||
qAdrszCarriageReturn: .quad szCarriageReturn |
|||
/***************************************************/ |
|||
/* ROUTINES INCLUDE */ |
|||
/***************************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeARM64.inc" |
|||
</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
~/.../rosetta/asm4 $ commandLine64 toto tutu |
|||
commandLine64 |
|||
toto |
|||
tutu |
|||
</pre> |
|||
=={{header|Ada}}== |
=={{header|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. |
In Ada95 and later versions, command line arguments are available through the predefined package Ada.Command_Line. In Ada83, this would be implementation dependent. |
||
< |
<syntaxhighlight lang="ada">with Ada.Command_line; use Ada.Command_Line; |
||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
Line 31: | Line 171: | ||
end loop; |
end loop; |
||
New_Line; |
New_Line; |
||
end Print_Commands;</ |
end Print_Commands;</syntaxhighlight> |
||
=== Alternative version using Matreshka === |
=== Alternative version using Matreshka === |
||
Line 37: | Line 177: | ||
Uses [http://forge.ada-ru.org/matreshka Matreshka] |
Uses [http://forge.ada-ru.org/matreshka Matreshka] |
||
< |
<syntaxhighlight lang="ada">with Ada.Wide_Wide_Text_IO; |
||
with League.Application; |
with League.Application; |
||
Line 48: | Line 188: | ||
(League.Application.Arguments.Element (J).To_Wide_Wide_String); |
(League.Application.Arguments.Element (J).To_Wide_Wide_String); |
||
end loop; |
end loop; |
||
end Main;</ |
end Main;</syntaxhighlight> |
||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
The arguments are passed to the program as a vector of strings called <em>args</em> |
The arguments are passed to the program as a vector of strings called <em>args</em> |
||
< |
<syntaxhighlight lang="aikido"> |
||
foreach arg in args { |
foreach arg in args { |
||
Line 58: | Line 198: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">integer i; |
||
i = 0; |
i = 0; |
||
Line 68: | Line 208: | ||
o_byte('\n'); |
o_byte('\n'); |
||
i += 1; |
i += 1; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386 - ''argc'' and ''argv'' are not part of the standard's prelude}} |
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386 - ''argc'' and ''argv'' are not part of the standard's prelude}} |
||
< |
<syntaxhighlight lang="algol68">main:( |
||
FOR i TO argc DO |
FOR i TO argc DO |
||
printf(($"the argument #"g(-0)" is "gl$, i, argv(i))) |
printf(($"the argument #"g(-0)" is "gl$, i, argv(i))) |
||
OD |
OD |
||
)</ |
)</syntaxhighlight> |
||
Linux command: |
Linux command: |
||
/usr/bin/a68g Command-line_arguments.a68 - 1 2 3 ... |
/usr/bin/a68g Command-line_arguments.a68 - 1 2 3 ... |
||
Line 88: | Line 228: | ||
the argument #6 is 3 |
the argument #6 is 3 |
||
the argument #7 is ... |
the argument #7 is ... |
||
</pre> |
|||
=={{header|Amazing Hopper}}== |
|||
<p>The main function "main(argv,argc)" is a macro-defined in HOPPER.H: get the arguments, and put them into array ARGV; ARGC have total arguments.</p> |
|||
<p>Macro MAIN(ARGV, ARGC):</p> |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#defn main(_V_,_N_) #RAND, main:, V#RNDV=1,_V_={#VOID}, \ |
|||
_N_=0,totalarg,mov(_N_), \ |
|||
LOOPGETARG_#RNDV:, {[ V#RNDV ]},push(_V_),++V#RNDV,\ |
|||
{_N_,V#RNDV},jle(LOOPGETARG_#RNDV),clear(V#RNDV) |
|||
</syntaxhighlight> |
|||
VERSION 1: |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#include <hopper.h> |
|||
main(argv, argc) |
|||
{"This program named: "},[1]get(argv),println |
|||
for(i=2, {i}lethan(argc),++i) |
|||
{"Argument #",i," = "}[i]get(argv),println |
|||
next |
|||
exit(0) |
|||
</syntaxhighlight> |
|||
VERSION 2: |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#include <hopper.h> |
|||
main: |
|||
total arg, argc=0,mov(argc) |
|||
{"This program named: ",[&1]},println |
|||
i=2 |
|||
__CNT_ARGS__: |
|||
{"Argumento #",i," = ",[&i]}println |
|||
++i,{argc,i}jle(__CNT_ARGS__) |
|||
exit(0) |
|||
</syntaxhighlight> |
|||
VERSION 3: |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#include <hopper.h> |
|||
main(argv, argc) |
|||
i=2 |
|||
#hl{ |
|||
print( "This program named: ",argv[1],"\n") |
|||
while( i <= argc ) |
|||
print("Argument #",i," = ",argv[i],"\n") |
|||
i += 1 |
|||
wend |
|||
} |
|||
exit(0) |
|||
</syntaxhighlight> |
|||
VERSION 4: |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#include <natural.h> |
|||
#include <hopper.h> |
|||
main: |
|||
get total arguments, and remember as 'total arguments'. |
|||
remember ("This program named: "), |
|||
now remember ( argument '1' ), and print with a new line. |
|||
secondly, declare 'i', take '2', and store in 'i' |
|||
do while ( variable 'i' is less or equal than 'total arguments', \ |
|||
consider this ( {"Argument #",i," = "} );\ |
|||
remember ( argument 'i' ); put a new line and print it; finally increment 'i' ). |
|||
exit(0) |
|||
</syntaxhighlight> |
|||
ETCETERA... |
|||
{{out}} |
|||
<pre> |
|||
xu@MrDalien:~/Proyectos/xuesp/HOPPER$ hopper src/args1.com 1 "Rosseta code" 100 |
|||
This program named: src/args1.com |
|||
Argumento #2 = 1 |
|||
Argumento #3 = Rosseta code |
|||
Argumento #4 = 100 |
|||
</pre> |
</pre> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript"> |
||
#!/usr/bin/env osascript |
#!/usr/bin/env osascript |
||
-- Print first argument |
-- Print first argument |
||
Line 98: | Line 310: | ||
return (item 1 of argv) |
return (item 1 of argv) |
||
end run |
end run |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi}} |
{{works with|as|Raspberry Pi}} |
||
<syntaxhighlight lang="arm assembly"> |
|||
<lang ARM Assembly> |
|||
/* ARM assembly Raspberry PI */ |
/* ARM assembly Raspberry PI */ |
||
/* program commandLine.s */ |
/* program commandLine.s */ |
||
Line 164: | Line 377: | ||
bx lr @ return |
bx lr @ return |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">loop arg 'a [ |
|||
print a |
|||
]</syntaxhighlight> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
From the AutoHotkey [http://www.autohotkey.com/docs/Scripts.htm documentation]: |
From the AutoHotkey [http://www.autohotkey.com/docs/Scripts.htm 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). " |
"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). " |
||
< |
<syntaxhighlight lang="autohotkey">Loop %0% ; number of parameters |
||
params .= %A_Index% . A_Space |
params .= %A_Index% . A_Space |
||
If params != |
If params != |
||
MsgBox, %0% parameters were passed:`n`n %params% |
MsgBox, %0% parameters were passed:`n`n %params% |
||
Else |
Else |
||
Run, %A_AhkPath% "%A_ScriptFullPath%" -c "\"alpha beta\"" -h "\"gamma\""</ |
Run, %A_AhkPath% "%A_ScriptFullPath%" -c "\"alpha beta\"" -h "\"gamma\""</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
||
BEGIN { |
BEGIN { |
||
Line 185: | Line 403: | ||
print "Argument " l " is " ARGV[l] |
print "Argument " l " is " ARGV[l] |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
Invoke Babel in interactive mode with arguments using the -i switch: |
Invoke Babel in interactive mode with arguments using the -i switch: |
||
<lang |
<syntaxhighlight lang="babel">babel -i Larry Mo Curly</syntaxhighlight> |
||
Print the argv list with newlines: |
Print the argv list with newlines: |
||
<lang |
<syntaxhighlight lang="babel">argv prn !</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 205: | Line 422: | ||
Print the argv list with spaces: |
Print the argv list with spaces: |
||
<lang |
<syntaxhighlight lang="babel">argv prs !</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 212: | Line 429: | ||
To access an individual argument, use the ith operator to select an element from the argv list; print with newline using say: |
To access an individual argument, use the ith operator to select an element from the argv list; print with newline using say: |
||
<lang |
<syntaxhighlight lang="babel">argv 1 ith say !</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 223: | Line 440: | ||
For most older BASICs that supply the keyword <code>COMMAND$</code>, 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.) |
For most older BASICs that supply the keyword <code>COMMAND$</code>, 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.) |
||
< |
<syntaxhighlight lang="qbasic">PRINT "args: '"; COMMAND$; "'"</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 232: | Line 449: | ||
FreeBASIC supplies three ways to retrieve the arguments: <code>COMMAND$</code> (which works identically to QuickBASIC's <code>COMMAND$</code>), <code>COMMAND$()</code> (a string array which works like [[#C|C]]'s <code>argv[]</code>), and <code>__FB_ARGV__</code> (an array of pointers which works even more like C's <code>argv[]</code>) and __FB_ARGC__ (which works like C's <code>argc</code>). |
FreeBASIC supplies three ways to retrieve the arguments: <code>COMMAND$</code> (which works identically to QuickBASIC's <code>COMMAND$</code>), <code>COMMAND$()</code> (a string array which works like [[#C|C]]'s <code>argv[]</code>), and <code>__FB_ARGV__</code> (an array of pointers which works even more like C's <code>argv[]</code>) and __FB_ARGC__ (which works like C's <code>argc</code>). |
||
< |
<syntaxhighlight lang="freebasic">DIM i AS INTEGER |
||
PRINT COMMAND$ |
PRINT COMMAND$ |
||
Line 245: | Line 462: | ||
FOR i = 0 TO __FB_ARGC__ - 1 |
FOR i = 0 TO __FB_ARGC__ - 1 |
||
PRINT "arg "; i; " = '"; *__FB_ARGV__[i]; "'" |
PRINT "arg "; i; " = '"; *__FB_ARGV__[i]; "'" |
||
NEXT i</ |
NEXT i</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 260: | Line 477: | ||
==={{header|BaCon}}=== |
==={{header|BaCon}}=== |
||
< |
<syntaxhighlight lang="freebasic">' Command line arguments including program name |
||
PRINT "Entire command line: ", ARGUMENT$ |
PRINT "Entire command line: ", ARGUMENT$ |
||
Line 268: | Line 485: | ||
PRINT " " & cli$[i]; |
PRINT " " & cli$[i]; |
||
NEXT |
NEXT |
||
PRINT</ |
PRINT</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 283: | Line 500: | ||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
{{works with|Windows NT|4 or later (includes Windows XP and onward)}} |
{{works with|Windows NT|4 or later (includes Windows XP and onward)}} |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
setlocal enabledelayedexpansion |
setlocal enabledelayedexpansion |
||
Line 297: | Line 514: | ||
for /l %%a in (1,1,%count%) do ( |
for /l %%a in (1,1,%count%) do ( |
||
echo !parameter[%%a]! |
echo !parameter[%%a]! |
||
)</ |
)</syntaxhighlight> |
||
Another way of doing it |
Another way of doing it |
||
< |
<syntaxhighlight lang="dos">::args2.cmd |
||
@echo off |
@echo off |
||
setlocal enabledelayedexpansion |
setlocal enabledelayedexpansion |
||
Line 323: | Line 540: | ||
for /l %%i in (1,1,%p#%) do ( |
for /l %%i in (1,1,%p#%) do ( |
||
echo p%%i=!p%%i! |
echo p%%i=!p%%i! |
||
)</ |
)</syntaxhighlight> |
||
Invocation: |
Invocation: |
||
< |
<syntaxhighlight lang="dos">>args2 foo "bar baz" quux |
||
fn=d:\bin\args2.cmd |
fn=d:\bin\args2.cmd |
||
p0=args2 |
p0=args2 |
||
Line 335: | Line 552: | ||
p2=bar baz |
p2=bar baz |
||
p3=quux |
p3=quux |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
<lang |
<syntaxhighlight lang="bbcbasic">PRINT @cmd$</syntaxhighlight> |
||
=={{header|Blue}}== |
|||
Linux/x86-64 |
|||
<syntaxhighlight lang="blue"> |
|||
global _start |
|||
: syscall ( num:eax -- result:eax | rcx ) syscall ; |
|||
: exit ( status:edi -- noret ) 60 syscall ; |
|||
: bye ( -- noret ) 0 exit ; |
|||
: die ( err:eax -- noret ) neg exit ; |
|||
: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ; |
|||
: ordie ( result -- ) unwrap drop ; |
|||
1 const stdout |
|||
: write ( buf:esi len:edx fd:edi -- ) 1 syscall ordie ; |
|||
: print ( buf len -- ) stdout write ; |
|||
: newline ( -- ) s" \n" print ; |
|||
: println ( buf len -- ) print newline ; |
|||
: find0 ( start:rsi -- end:rsi ) lodsb 0 cmp latest xne ; |
|||
: cstrlen ( str:rdi -- len:rsi ) dup find0 swap sub dec ; |
|||
: cstr>str ( cstr:rdx -- str:rsi len:rdx ) dup cstrlen xchg ; |
|||
: print-arg ( arg -- ) cstr>str println ; |
|||
: _start ( rsp -- noret ) dup @ swap |
|||
: print-args ( argc:rcx argv:rsp -- noret ) |
|||
8 add @ print-arg latest loop |
|||
bye |
|||
; |
|||
</syntaxhighlight> |
|||
=={{header|BQN}}== |
|||
BQN has a system value for getting pre-parsed command line arguments. |
|||
<syntaxhighlight lang="text">•Show •args</syntaxhighlight> |
|||
should show the full list of args. |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
When Bracmat is started with one or more arguments, each argument is evaluated as if it were a Bracmat expression <i>unless</i> an argument (for example the first one) consumes the next argument(s) by calling <code>arg$</code>. Each invocation of <code>arg$</code> pops one argument from the remaining list of arguments. Calling <code>arg$</code> 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. |
When Bracmat is started with one or more arguments, each argument is evaluated as if it were a Bracmat expression <i>unless</i> an argument (for example the first one) consumes the next argument(s) by calling <code>arg$</code>. Each invocation of <code>arg$</code> pops one argument from the remaining list of arguments. Calling <code>arg$</code> 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. |
||
<lang>whl'(arg$:?a&out$(str$("next arg=" !a)))</ |
<syntaxhighlight lang="text">whl'(arg$:?a&out$(str$("next arg=" !a)))</syntaxhighlight> |
||
Now run Bracmat with this program as the first argument in a DOS environment: |
Now run Bracmat with this program as the first argument in a DOS environment: |
||
<pre>bracmat "whl'(arg$:?a&out$(str$(\"next arg=\" !a)))" "a" /b -c 2+3 'd;' "out$(\"13+7=\" 13+7)"</pre> |
<pre>bracmat "whl'(arg$:?a&out$(str$(\"next arg=\" !a)))" "a" /b -c 2+3 'd;' "out$(\"13+7=\" 13+7)"</pre> |
||
Line 375: | Line 636: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="c">#include <stdlib.h> |
||
#include <stdio.h> |
#include <stdio.h> |
||
Line 385: | Line 646: | ||
(void) printf("the argument #%d is %s\n", i, argv[i]); |
(void) printf("the argument #%d is %s\n", i, argv[i]); |
||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
|||
Command line arguments are passed the same way as in C. |
|||
This example uses iostream. Traditional C I/O also works. |
|||
<lang cpp>#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; |
|||
}</lang> |
|||
=={{header|C sharp|C#}}== |
=={{header|C sharp|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. |
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. |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace RosettaCode { |
namespace RosettaCode { |
||
Line 415: | Line 659: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace RosettaCode { |
namespace RosettaCode { |
||
Line 428: | Line 672: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
|||
Command line arguments are passed the same way as in C. |
|||
This example uses <code><iostream></code>. C-style i/o also works. |
|||
<syntaxhighlight lang="cpp">#include <iostream> |
|||
int main(int argc, const char* argv[]) { |
|||
std::cout << "This program is named " << argv[0] << '\n' |
|||
<< "There are " << argc - 1 << " arguments given.\n"; |
|||
for (int i = 1; i < argc; ++i) |
|||
std::cout << "The argument #" << i << " is " << argv[i] << '\n'; |
|||
}</syntaxhighlight> |
|||
=={{header|C3}}== |
|||
Command line arguments are passed to main and will be converted to UTF-8 strings on all platforms. |
|||
<syntaxhighlight lang="c3">import std::io; |
|||
fn void main(String[] args) |
|||
{ |
|||
io::printfn("This program is named %s.", args[0]); |
|||
for (int i = 1; i < args.len; i++) |
|||
{ |
|||
io::printfn("the argument #%d is %s\n", i, args[i]); |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|Clean}}== |
=={{header|Clean}}== |
||
<tt>getCommandLine</tt> from the module <tt>ArgEnv</tt> returns an array of command-line arguments (the first element is the name of the program). |
<tt>getCommandLine</tt> from the module <tt>ArgEnv</tt> returns an array of command-line arguments (the first element is the name of the program). |
||
< |
<syntaxhighlight lang="clean">import ArgEnv |
||
Start = getCommandLine</ |
Start = getCommandLine</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 441: | Line 715: | ||
The value of ''*command-line-args*'' is a sequence of the supplied command line arguments, or ''nil'' if none were supplied. |
The value of ''*command-line-args*'' is a sequence of the supplied command line arguments, or ''nil'' if none were supplied. |
||
< |
<syntaxhighlight lang="clojure">(dorun (map println *command-line-args*))</syntaxhighlight> |
||
=={{header|CLU}}== |
|||
While it is not part of the language standard as specified in the reference manual, |
|||
[[Portable CLU]] includes a library function <code>get_argv</code> which returns |
|||
all the arguments in order. |
|||
Note that unlike C, the program name itself is not included in the list of arguments. |
|||
<syntaxhighlight lang="clu">% This program needs to be merged with PCLU's "useful.lib", |
|||
% where get_argv lives. |
|||
% |
|||
% pclu -merge $CLUHOME/lib/useful.lib -compile cmdline.clu |
|||
start_up = proc () |
|||
po: stream := stream$primary_output() |
|||
args: sequence[string] := get_argv() |
|||
for arg: string in sequence[string]$elements(args) do |
|||
stream$putl(po, "arg: " || arg) |
|||
end |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ ./cmdline -c "alpha beta" -h "gamma" |
|||
arg: -c |
|||
arg: alpha beta |
|||
arg: -h |
|||
arg: gamma</pre> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Line 450: | Line 753: | ||
Getting the arguments in one go, exactly as they were passed in: |
Getting the arguments in one go, exactly as they were passed in: |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. accept-all-args. |
PROGRAM-ID. accept-all-args. |
||
Line 463: | Line 766: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
Getting the arguments one at a time, with arguments being split by whitespace if not in quotes: |
Getting the arguments one at a time, with arguments being split by whitespace if not in quotes: |
||
< |
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION. |
||
PROGRAM-ID. accept-args-one-at-a-time. |
PROGRAM-ID. accept-args-one-at-a-time. |
||
Line 482: | Line 785: | ||
GOBACK |
GOBACK |
||
.</ |
.</syntaxhighlight> |
||
Passing arguments from UNIX/Linux Systems to COBOL. |
Passing arguments from UNIX/Linux Systems to COBOL. |
||
{{works with|OpenCOBOL}} |
{{works with|OpenCOBOL}} |
||
{{works with|gnuCOBOL}} |
{{works with|gnuCOBOL}} |
||
< |
<syntaxhighlight lang="cobol"> |
||
*>Created By Zwiegnet 8/19/2004 |
*>Created By Zwiegnet 8/19/2004 |
||
Line 544: | Line 847: | ||
STOP RUN. |
STOP RUN. |
||
.</ |
.</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
{{works with|Node.js}} |
{{works with|Node.js}} |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
console.log arg for arg in process.argv |
console.log arg for arg in process.argv |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 558: | Line 861: | ||
The following function could be used to create a uniform way to access the arguments: |
The following function could be used to create a uniform way to access the arguments: |
||
< |
<syntaxhighlight lang="lisp">(defun argv () |
||
(or |
(or |
||
#+clisp (ext:argv) |
#+clisp (ext:argv) |
||
Line 569: | Line 872: | ||
#+allegro (sys:command-line-arguments) |
#+allegro (sys:command-line-arguments) |
||
#+lispworks sys:*line-arguments-list* |
#+lispworks sys:*line-arguments-list* |
||
nil))</ |
nil))</syntaxhighlight> |
||
=={{header|Cowgol}}== |
|||
Cowgol includes a function to retrieve command-line arguments in its standard library. |
|||
The manner in which arguments are parsed is, however, dependent on the operating system. |
|||
<syntaxhighlight lang="cowgol">include "cowgol.coh"; |
|||
include "argv.coh"; |
|||
ArgvInit(); |
|||
var i: uint8 := 0; |
|||
loop |
|||
var arg := ArgvNext(); |
|||
if arg == 0 as [uint8] then break; end if; |
|||
i := i + 1; |
|||
print_i8(i); |
|||
print(": '"); |
|||
print(arg); |
|||
print("'\n"); |
|||
end loop;</syntaxhighlight> |
|||
{{out}} |
|||
On Linux: |
|||
<pre>$ ./args -c "alpha beta" -h "gamma" |
|||
1: '-c' |
|||
2: 'alpha beta' |
|||
3: '-h' |
|||
4: 'gamma'</pre> |
|||
On CP/M: |
|||
<pre>A>args -c "alpha beta" -h "gamma" |
|||
1: '-C' |
|||
2: '"ALPHA' |
|||
3: 'BETA"' |
|||
4: '-H' |
|||
5: '"GAMMA"'</pre> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">void main(in string[] args) { |
||
import std.stdio; |
import std.stdio; |
||
foreach (immutable i, arg; args[1 .. $]) |
foreach (immutable i, arg; args[1 .. $]) |
||
writefln("#%2d : %s", i + 1, arg); |
writefln("#%2d : %s", i + 1, arg); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Dart}}== |
|||
<syntaxhighlight lang="csharp">main(List<String> args) { |
|||
for(var arg in args) |
|||
print(arg); |
|||
}</syntaxhighlight> |
|||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
case is not preserved unless the parameter is in quotes |
case is not preserved unless the parameter is in quotes |
||
< |
<syntaxhighlight lang="dcl">$ i = 1 |
||
$ loop: |
$ loop: |
||
$ write sys$output "the value of P''i' is ", p'i |
$ write sys$output "the value of P''i' is ", p'i |
||
$ i = i + 1 |
$ i = i + 1 |
||
$ if i .le. 8 then $ goto loop</ |
$ if i .le. 8 then $ goto loop</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ @command_line_arguments -c "alpha beta" -h "gamma" |
<pre>$ @command_line_arguments -c "alpha beta" -h "gamma" |
||
Line 595: | Line 941: | ||
the value of P7 is |
the value of P7 is |
||
the value of P8 is</pre> |
the value of P8 is</pre> |
||
=={{header|Delphi}}== |
|||
<syntaxhighlight lang="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 |
|||
</syntaxhighlight> |
|||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
Command line arguments are found in <code>!args</code> and <code>!opts</code>. |
Command line arguments are found in <code>!args</code> and <code>!opts</code>. |
||
< |
<syntaxhighlight lang="dejavu">for i range 0 -- len !args: |
||
print\( "Argument #" i " is " ) |
print\( "Argument #" i " is " ) |
||
. get-from !args i |
. get-from !args i |
||
Line 607: | Line 970: | ||
if has !opts :four: |
if has !opts :four: |
||
!. get-from !opts :four</ |
!. get-from !opts :four</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ vu args-3.deja one two -c three --four=five |
<pre>$ vu args-3.deja one two -c three --four=five |
||
Line 619: | Line 982: | ||
The order of command line ''options'' is lost. |
The order of command line ''options'' is lost. |
||
=={{header| |
=={{header|Draco}}== |
||
Draco comes with a library function that will return each command line argument |
|||
in turn. It simply splits the command line on whitespace, and does not support |
|||
quotes. |
|||
In the example below, the arguments are additionally all made uppercase. |
|||
<lang delphi>// The program name and the directory it was called from are in |
|||
This is however a limitation of the CP/M operating system, and not of Draco. |
|||
// param[0] , so given the axample of myprogram -c "alpha beta" -h "gamma" |
|||
<syntaxhighlight lang="draco">\util.g |
|||
for x := 0 to paramcount do |
|||
writeln('param[',x,'] = ',param[x]); |
|||
proc nonrec main() void: |
|||
// will yield ( assuming windows and the c drive as the only drive) : |
|||
*char par; |
|||
word i; |
|||
i := 0; |
|||
while par := GetPar(); par ~= nil do |
|||
i := i + 1; |
|||
writeln(i:3, ": '", par, "'") |
|||
od |
|||
corp</syntaxhighlight> |
|||
{{out}} |
|||
// param[0] = c:\myprogram |
|||
// param[1] = -c |
|||
<pre>A>param -c "alpha beta" -h "gamma" |
|||
1: '-C' |
|||
2: '"ALPHA' |
|||
// param[4] = gamma |
|||
3: 'BETA"' |
|||
</lang> |
|||
4: '-H' |
|||
5: '"GAMMA"'</pre> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
<lang |
<syntaxhighlight lang="e">interp.getArgs()</syntaxhighlight> |
||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
Line 644: | Line 1,019: | ||
This class inherits functionality for dealing with command line arguments from class <code lang="eiffel">ARGUMENTS</code>. It uses the feature <code lang="eiffel">separate_character_option_value</code> to return the values by option name for each of the two arguments. |
This class inherits functionality for dealing with command line arguments from class <code lang="eiffel">ARGUMENTS</code>. It uses the feature <code lang="eiffel">separate_character_option_value</code> to return the values by option name for each of the two arguments. |
||
< |
<syntaxhighlight lang="eiffel ">class |
||
APPLICATION |
APPLICATION |
||
inherit |
inherit |
||
Line 660: | Line 1,035: | ||
io.read_line -- Keep console window open |
io.read_line -- Keep console window open |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Output (for command line arguments: -c "alpha beta" -h "gamma"): |
Output (for command line arguments: -c "alpha beta" -h "gamma"): |
||
Line 669: | Line 1,044: | ||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA |
ELENA 6.x : |
||
< |
<syntaxhighlight lang="elena">import system'routines; |
||
import extensions; |
import extensions; |
||
public program() |
public program() |
||
{ |
{ |
||
program_arguments.forEvery:(int i) |
program_arguments.forEvery::(int i) |
||
{ console.printLine("Argument ",i," is ",program_arguments[i]) } |
{ console.printLine("Argument ",i," is ",program_arguments[i]) } |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 689: | Line 1,064: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
Elixir provides command line arguments via the <tt>System.argv()</tt> function. |
Elixir provides command line arguments via the <tt>System.argv()</tt> function. |
||
< |
<syntaxhighlight lang="elixir">#!/usr/bin/env elixir |
||
IO.puts 'Arguments:' |
IO.puts 'Arguments:' |
||
Enum.map(System.argv(),&IO.puts(&1))</ |
Enum.map(System.argv(),&IO.puts(&1))</syntaxhighlight> |
||
Example run: |
Example run: |
||
< |
<syntaxhighlight lang="bash">$ ./show-args.exs a b=2 --3 -4 |
||
Arguments: |
Arguments: |
||
a |
a |
||
b=2 |
b=2 |
||
--3 |
--3 |
||
-4</ |
-4</syntaxhighlight> |
||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
<lang emacslisp> |
|||
<syntaxhighlight lang="lisp">(while argv |
|||
#!/usr/bin/env emacs --script |
|||
(message "Argument: %S" (pop argv)))</syntaxhighlight> |
|||
(dolist (arg command-line-args-left) (message arg)) |
|||
</lang> |
|||
Invoke script: |
|||
emacs --script test.el foo bar baz |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
When used as a script language the arguments is a list to the main/1 function. When compiled use init:get_arguments/0 |
When used as a script language the arguments is a list to the main/1 function. When compiled use init:get_arguments/0 |
||
<lang |
<syntaxhighlight lang="erlang">3> init:get_arguments().</syntaxhighlight> |
||
result |
result |
||
< |
<syntaxhighlight lang="erlang">[{root,["/usr/erlang/erl5.5"]}, |
||
{progname,["erl"]}, |
{progname,["erl"]}, |
||
{home,["/home/me"]}, |
{home,["/home/me"]}, |
||
{c,["alpha beta"]}, |
{c,["alpha beta"]}, |
||
{h,["gamma"]}]</ |
{h,["gamma"]}]</syntaxhighlight> |
||
init:get_argument(name) can be used to fetch value of a particular flag |
init:get_argument(name) can be used to fetch value of a particular flag |
||
< |
<syntaxhighlight lang="erlang">4> init:get_argument(h). |
||
{ok,[["gamma"]]} |
{ok,[["gamma"]]} |
||
5> init:get_argument(c). |
5> init:get_argument(c). |
||
{ok,[["alpha beta"]]}</ |
{ok,[["alpha beta"]]}</syntaxhighlight> |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">constant cmd = command_line() |
||
printf(1,"Interpreter/executable name: %s\n",{cmd[1]}) |
printf(1,"Interpreter/executable name: %s\n",{cmd[1]}) |
||
printf(1,"Program file name: %s\n",{cmd[2]}) |
printf(1,"Program file name: %s\n",{cmd[2]}) |
||
Line 732: | Line 1,110: | ||
printf(1,"#%d : %s\n",{i,cmd[i]}) |
printf(1,"#%d : %s\n",{i,cmd[i]}) |
||
end for |
end for |
||
end if</ |
end if</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|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. |
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. |
||
< |
<syntaxhighlight lang="fsharp">#light |
||
[<EntryPoint>] |
[<EntryPoint>] |
||
let main args = |
let main args = |
||
Array.iter (fun x -> printfn "%s" x) args |
Array.iter (fun x -> printfn "%s" x) args |
||
0</ |
0</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
USING: io sequences command-line ; |
USING: io sequences command-line ; |
||
Line 746: | Line 1,125: | ||
=={{header|Fancy}}== |
=={{header|Fancy}}== |
||
< |
<syntaxhighlight lang="fancy">ARGV each: |a| { |
||
a println # print each given command line argument |
a println # print each given command line argument |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 760: | Line 1,139: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Line 766: | Line 1,145: | ||
{{works with|gforth|0.6.2}} |
{{works with|gforth|0.6.2}} |
||
< |
<syntaxhighlight lang="forth">\ args.f: print each command line argument on a separate line |
||
: main |
: main |
||
argc @ 0 do i arg type cr loop ; |
argc @ 0 do i arg type cr loop ; |
||
main bye</ |
main bye</syntaxhighlight> |
||
Here is output from a sample run. |
Here is output from a sample run. |
||
< |
<syntaxhighlight lang="forth">$ gforth args.f alpha "beta gamma" delta |
||
gforth |
gforth |
||
args.f |
args.f |
||
Line 779: | Line 1,158: | ||
beta gamma |
beta gamma |
||
delta |
delta |
||
$</ |
$</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|2003 and later}} |
{{works with|Fortran|2003 and later}} |
||
< |
<syntaxhighlight lang="fortran">program command_line_arguments |
||
implicit none |
implicit none |
||
Line 798: | Line 1,178: | ||
end program command_line_arguments |
end program command_line_arguments |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note: This sample uses the Fortran 2003 intrinsic routines <code>command_argument_count</code> and <code>get_command_argument</code> instead of the nonstandard extensions <code>iargc</code> and <code>getarg</code>. Most Fortran compilers support both. |
Note: This sample uses the Fortran 2003 intrinsic routines <code>command_argument_count</code> and <code>get_command_argument</code> instead of the nonstandard extensions <code>iargc</code> and <code>getarg</code>. Most Fortran compilers support both. |
||
Sample usage: |
Sample usage: |
||
<lang>> ./a.out -c "alpha beta" -h "gamma" |
<syntaxhighlight lang="text">> ./a.out -c "alpha beta" -h "gamma" |
||
./a.out |
./a.out |
||
-c |
-c |
||
alpha beta |
alpha beta |
||
-h |
-h |
||
gamma</ |
gamma</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
' Program (myprogram.exe) invoke as follows: |
' Program (myprogram.exe) invoke as follows: |
||
Line 818: | Line 1,198: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 827: | Line 1,207: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
Arguments to a program are available in the <CODE>ARGS</CODE> array variable. |
Arguments to a program are available in the <CODE>ARGS</CODE> array variable. |
||
< |
<syntaxhighlight lang="frink"> |
||
println[ARGS] |
println[ARGS] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
<lang |
<syntaxhighlight lang="funl">println( args )</syntaxhighlight> |
||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=a1374aa441520314ad0c7decb1e91c97 Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=a1374aa441520314ad0c7decb1e91c97 Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">PUBLIC SUB main() |
||
DIM l AS Integer |
DIM l AS Integer |
||
DIM numparms AS Integer |
DIM numparms AS Integer |
||
Line 845: | Line 1,225: | ||
PRINT l; " : "; parm |
PRINT l; " : "; parm |
||
NEXT |
NEXT |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Genie}}== |
=={{header|Genie}}== |
||
< |
<syntaxhighlight lang="genie">[indent=4] |
||
/* |
/* |
||
Command line arguments, in Genie |
Command line arguments, in Genie |
||
Line 867: | Line 1,247: | ||
// to reiterate, args[0] is the command |
// to reiterate, args[0] is the command |
||
if args[0] is not null |
if args[0] is not null |
||
print "\nWith Genie, args[0] is the command: %s", args[0]</ |
print "\nWith Genie, args[0] is the command: %s", args[0]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 886: | Line 1,266: | ||
This uses the <code>gsio</code> I/O operations, which are designed to be simple to implement on top of Haskell and simple to use. It also uses impmapM, which is a specific specialization of mapM for the HSGS implementation. |
This uses the <code>gsio</code> I/O operations, which are designed to be simple to implement on top of Haskell and simple to use. It also uses impmapM, which is a specific specialization of mapM for the HSGS implementation. |
||
< |
<syntaxhighlight lang="global script">λ 'as. impmapM (λ 'a. print qq{Argument: §(a)\n}) as</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
<syntaxhighlight lang="go"> |
|||
<lang go> |
|||
package main |
package main |
||
import ( |
import ( |
||
Line 901: | Line 1,281: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Command-line arguments are accessible via the '''args''' list variable. The following is saved as the file "Echo.groovy": |
Command-line arguments are accessible via the '''args''' list variable. The following is saved as the file "Echo.groovy": |
||
<lang |
<syntaxhighlight lang="groovy">println args</syntaxhighlight> |
||
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: |
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: |
||
Line 918: | Line 1,298: | ||
=={{header|Harbour}}== |
=={{header|Harbour}}== |
||
Uses the Harbour-specific hb_PValue() function |
Uses the Harbour-specific hb_PValue() function |
||
< |
<syntaxhighlight lang="visualfoxpro">PROCEDURE Main() |
||
LOCAL i |
LOCAL i |
||
Line 926: | Line 1,306: | ||
NEXT |
NEXT |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Line 933: | Line 1,313: | ||
myprog.hs: |
myprog.hs: |
||
< |
<syntaxhighlight lang="haskell">import System |
||
main = getArgs >>= print</ |
main = getArgs >>= print</syntaxhighlight> |
||
<pre> |
<pre> |
||
myprog a -h b c |
myprog a -h b c |
||
Line 941: | Line 1,321: | ||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">DO i = 2, 100 ! 1 is HicEst.exe |
||
EDIT(Text=$CMD_LINE, SePaRators='-"', ITeM=i, IF ' ', EXit, ENDIF, Parse=cmd, GetPosition=position) |
EDIT(Text=$CMD_LINE, SePaRators='-"', ITeM=i, IF ' ', EXit, ENDIF, Parse=cmd, GetPosition=position) |
||
IF(position > 0) WRITE(Messagebox) cmd |
IF(position > 0) WRITE(Messagebox) cmd |
||
ENDDO</ |
ENDDO</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Command line parameters are passed to Icon/Unicon programs as a list of strings. |
Command line parameters are passed to Icon/Unicon programs as a list of strings. |
||
< |
<syntaxhighlight lang="icon">procedure main(arglist) |
||
every write(!arglist) |
every write(!arglist) |
||
end</ |
end</syntaxhighlight> |
||
{{libheader|Icon Programming Library}} includes [http://www.cs.arizona.edu/icon/library/procs/options.htm options] that parses the command line as switches and arguments and returns the results in a table. |
{{libheader|Icon Programming Library}} includes [http://www.cs.arizona.edu/icon/library/procs/options.htm options] that parses the command line as switches and arguments and returns the results in a table. |
||
=={{header|Io}}== |
=={{header|Io}}== |
||
< |
<syntaxhighlight lang="io">System args foreach(a, a println)</syntaxhighlight> |
||
=={{header|Ioke}}== |
=={{header|Ioke}}== |
||
<lang |
<syntaxhighlight lang="ioke">System programArguments each(println)</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 964: | Line 1,344: | ||
The global <code>ARGV</code> holds the command line arguments. Thus, a program to display them: |
The global <code>ARGV</code> holds the command line arguments. Thus, a program to display them: |
||
<lang |
<syntaxhighlight lang="j"> ARGV</syntaxhighlight> |
||
In a non-interactive context, we would instead use <code>echo ARGV</code>. |
|||
=={{header|Java}}== |
|||
=={{header|Jakt}}== |
|||
<lang java>public class Arguments { |
|||
The main function can recieve the command line arguments as an arbitrarily named array of String. argv[0] will be the name of the program. |
|||
<syntaxhighlight lang="jakt"> |
|||
fn main(arguments: [String]) { |
|||
println("{}", arguments) |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Java}}== |
|||
The arguments will be passed to <code>main</code> as the only parameter.<br /> |
|||
The array is non-null. |
|||
<syntaxhighlight lang="java"> |
|||
public static void main(String[] args) |
|||
</syntaxhighlight> |
|||
Running this command |
|||
<syntaxhighlight lang="bash"> |
|||
myprogram -c "alpha beta" -h "gamma" |
|||
</syntaxhighlight> |
|||
Will produce the following |
|||
<pre> |
|||
-c |
|||
alpha beta |
|||
-h |
|||
gamma |
|||
</pre> |
|||
<br /> |
|||
And alternate demonstration. |
|||
<syntaxhighlight lang="java">public class Arguments { |
|||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
System.out.println("There are " + args.length + " arguments given."); |
System.out.println("There are " + args.length + " arguments given."); |
||
Line 974: | Line 1,382: | ||
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); |
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
For more sophisticated command-line option and option-argument parsing use the [http://commons.apache.org/cli '''Apache Commons CLI'''] (command-line interface) library. |
For more sophisticated command-line option and option-argument parsing use the [http://commons.apache.org/cli '''Apache Commons CLI'''] (command-line interface) library. |
||
Line 980: | Line 1,388: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
{{works with|Node.js}} |
{{works with|Node.js}} |
||
< |
<syntaxhighlight lang="javascript">process.argv.forEach((val, index) => { |
||
console.log(`${index}: ${val}`); |
console.log(`${index}: ${val}`); |
||
});</ |
});</syntaxhighlight> |
||
{{works with|JScript}} |
{{works with|JScript}} |
||
< |
<syntaxhighlight lang="javascript">var objArgs = WScript.Arguments; |
||
for (var i = 0; i < objArgs.length; i++) |
for (var i = 0; i < objArgs.length; i++) |
||
WScript.Echo(objArgs.Item(i));</ |
WScript.Echo(objArgs.Item(i));</syntaxhighlight> |
||
{{works with|JScript.NET (compiled with jsc.exe)}} |
{{works with|JScript.NET (compiled with jsc.exe)}} |
||
< |
<syntaxhighlight lang="javascript">import System; |
||
var argv:String[] = Environment.GetCommandLineArgs(); |
var argv:String[] = Environment.GetCommandLineArgs(); |
||
for (var i in argv) |
for (var i in argv) |
||
print(argv[i]);</ |
print(argv[i]);</syntaxhighlight> |
||
{{works with|Rhino}} |
{{works with|Rhino}} |
||
{{works with|SpiderMonkey}} |
{{works with|SpiderMonkey}} |
||
< |
<syntaxhighlight lang="javascript">for (var i = 0; i < arguments.length; i++) |
||
print(arguments[i]);</ |
print(arguments[i]);</syntaxhighlight> |
||
=={{header|Joy}}== |
|||
<syntaxhighlight lang="joy">#!/usr/bin/joy |
|||
argv rest put.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>["-c" "alpha beta" "-h" "gamma"]</pre> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 1,014: | Line 1,429: | ||
$ jq -n '$ARGS' --args a b |
$ jq -n '$ARGS' --args a b |
||
yields:< |
yields:<syntaxhighlight lang="json">{ |
||
"positional": [ |
"positional": [ |
||
"a", |
"a", |
||
Line 1,020: | Line 1,435: | ||
], |
], |
||
"named": {} |
"named": {} |
||
}</ |
}</syntaxhighlight> |
||
Arguments specified with ''--args'' are always read as JSON strings; arguments specified with ''--jsonargs'' |
Arguments specified with ''--args'' are always read as JSON strings; arguments specified with ''--jsonargs'' |
||
Line 1,039: | Line 1,454: | ||
=={{header|Jsish}}== |
=={{header|Jsish}}== |
||
< |
<syntaxhighlight lang="javascript">#!/usr/local/bin/jsish |
||
puts(Info.argv0()); |
puts(Info.argv0()); |
||
puts(console.args);</ |
puts(console.args);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,049: | Line 1,464: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Works when the Julia program is run as a file argument to julia.exe. |
|||
<lang Julia> |
|||
<syntaxhighlight lang="julia">using Printf |
|||
prog = basename(Base.source_path()) |
|||
prog = Base.basename(Base.source_path()) |
|||
println(prog, "'s command-line arguments are:") |
println(prog, "'s command-line arguments are:") |
||
Line 1,056: | Line 1,473: | ||
println(" ", s) |
println(" ", s) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 1,073: | Line 1,490: | ||
per line: |
per line: |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
.p'.a |
.p'.a |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang="scala">fun main(args: Array<String>) { |
||
println("There are " + args.size + " arguments given.") |
println("There are " + args.size + " arguments given.") |
||
args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") } |
args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") } |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
See Java output. |
See Java output. |
||
=={{header|Lang}}== |
|||
In lang command line arguments are stored in &LANG_ARGS. |
|||
<syntaxhighlight lang="lang"> |
|||
$ele |
|||
foreach($[ele], &LANG_ARGS) { |
|||
fn.println($ele) |
|||
} |
|||
</syntaxhighlight> |
|||
Calling a Lang program with command line arguments depends on the implementation. |
|||
The following example shows, how this can be achieved in Standard Lang (-- defines the start of the command line arguments for the Lang program): |
|||
<syntaxhighlight lang="shell"> |
|||
$ lang cmdarg.lang -- 2 abc test text |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2 |
|||
abc |
|||
test |
|||
text |
|||
</pre> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9 |
||
iterate($argv) => { |
iterate($argv) => { |
||
stdoutnl("Argument " + loop_count + ": " + loop_value) |
stdoutnl("Argument " + loop_count + ": " + loop_value) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="shell">$ lasso9 arguments.lasso -c "alpha beta" -h "gamma" |
||
Argument 1: arguments.lasso |
Argument 1: arguments.lasso |
||
Argument 2: -c |
Argument 2: -c |
||
Argument 3: alpha beta |
Argument 3: alpha beta |
||
Argument 4: -h |
Argument 4: -h |
||
Argument 5: gamma</ |
Argument 5: gamma</syntaxhighlight> |
||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
To demonstrate this, we can start the LFE REPL up with the parameters for this example: |
To demonstrate this, we can start the LFE REPL up with the parameters for this example: |
||
< |
<syntaxhighlight lang="shell"> |
||
$ ./bin/lfe -pa ebin/ -c "alpha beta" -h "gamma" |
$ ./bin/lfe -pa ebin/ -c "alpha beta" -h "gamma" |
||
</syntaxhighlight> |
|||
</lang> |
|||
Once we're in the shell, we can get all the initializing arguments with this call: |
Once we're in the shell, we can get all the initializing arguments with this call: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (: init get_arguments) |
> (: init get_arguments) |
||
(#(root ("/opt/erlang/r15b03")) |
(#(root ("/opt/erlang/r15b03")) |
||
Line 1,117: | Line 1,555: | ||
#(c ("alpha beta")) |
#(c ("alpha beta")) |
||
#(h ("gamma"))) |
#(h ("gamma"))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
We can also get specific arguments if we know their keys: |
We can also get specific arguments if we know their keys: |
||
< |
<syntaxhighlight lang="lisp"> |
||
> (: init get_argument 'c) |
> (: init get_argument 'c) |
||
#(ok (("alpha beta"))) |
#(ok (("alpha beta"))) |
||
> (: init get_argument 'h) |
> (: init get_argument 'h) |
||
#(ok (("gamma"))) |
#(ok (("gamma"))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<lang |
<syntaxhighlight lang="lb">print CommandLine$</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang="lingo">put the commandline |
||
-- "-c alpha beta -h gamma"</ |
-- "-c alpha beta -h gamma"</syntaxhighlight> |
||
In latest versions of Mac OS X, the above approach doesn't work anymore. But there is a free "Xtra" (binary plugin/shared library) called "CommandLine Xtra" that works both in Windows and Mac OS X and returns the command-line parsed into a lingo list (array): |
In latest versions of Mac OS X, the above approach doesn't work anymore. But there is a free "Xtra" (binary plugin/shared library) called "CommandLine Xtra" that works both in Windows and Mac OS X and returns the command-line parsed into a lingo list (array): |
||
{{libheader|CommandLine Xtra}} |
{{libheader|CommandLine Xtra}} |
||
< |
<syntaxhighlight lang="lingo">put getCommandLineArgs() |
||
-- ["-c", "alpha beta", "-h", "gamma"]</ |
-- ["-c", "alpha beta", "-h", "gamma"]</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
Line 1,145: | Line 1,583: | ||
logo file.logo - arg1 arg2 arg3 |
logo file.logo - arg1 arg2 arg3 |
||
Then the arguments after the "-" are found in a list in variable :COMMAND.LINE |
Then the arguments after the "-" are found in a list in variable :COMMAND.LINE |
||
< |
<syntaxhighlight lang="logo">show :COMMAND.LINE |
||
[arg1 arg2 arg3]</ |
[arg1 arg2 arg3]</syntaxhighlight> |
||
Alternatively, make the first line of an executable logo script: |
Alternatively, make the first line of an executable logo script: |
||
#! /usr/bin/logo - |
#! /usr/bin/logo - |
||
Line 1,153: | Line 1,591: | ||
=={{header|LSE64}}== |
=={{header|LSE64}}== |
||
< |
<syntaxhighlight lang="lse64">argc , nl # number of arguments (including command itself) |
||
0 # argument |
0 # argument |
||
dup arg dup 0 = || ,t 1 + repeat |
dup arg dup 0 = || ,t 1 + repeat |
||
drop</ |
drop</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|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: |
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: |
||
< |
<syntaxhighlight lang="lua">print( "Program name:", arg[0] ) |
||
print "Arguments:" |
print "Arguments:" |
||
for i = 1, #arg do |
for i = 1, #arg do |
||
print( i," ", arg[i] ) |
print( i," ", arg[i] ) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
function quote$("a") return "a" a string in "" |
function quote$("a") return "a" a string in "" |
||
Line 1,174: | Line 1,614: | ||
For this example we make a script, save to temporary directory, and call it passing arguments. We can use Win as shell substitute in M2000 environment, or the Use statement. Reading the shell statement Win we can see how the command line composed. We call the m2000.exe in the appdir$ (application directory, is the path to M2000.exe), and pass a string as a file with a path. That path will be the current path for the new start of m2000.exe the host for M2000 Interpreter (an activeX dll). |
For this example we make a script, save to temporary directory, and call it passing arguments. We can use Win as shell substitute in M2000 environment, or the Use statement. Reading the shell statement Win we can see how the command line composed. We call the m2000.exe in the appdir$ (application directory, is the path to M2000.exe), and pass a string as a file with a path. That path will be the current path for the new start of m2000.exe the host for M2000 Interpreter (an activeX dll). |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
Document a$ = { |
Document a$ = { |
||
Line 1,201: | Line 1,641: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
=={{header|Mathematica}}== |
|||
myprogram: |
myprogram: |
||
< |
<syntaxhighlight lang="mathematica">#!/usr/local/bin/MathematicaScript -script |
||
$CommandLine</ |
$CommandLine</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>{myprogram,-c,alpha beta,-h,gamma}</pre> |
<pre>{myprogram,-c,alpha beta,-h,gamma}</pre> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
<lang> |
<syntaxhighlight lang="text"> |
||
:- module cmd_line_args. |
:- module cmd_line_args. |
||
:- interface. |
:- interface. |
||
Line 1,232: | Line 1,671: | ||
print_arg(Arg, ArgNum, ArgNum + 1, !IO) :- |
print_arg(Arg, ArgNum, ArgNum + 1, !IO) :- |
||
io.format("the argument #%d is %s\n", [i(ArgNum), s(Arg)], !IO). |
io.format("the argument #%d is %s\n", [i(ArgNum), s(Arg)], !IO). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
<lang |
<syntaxhighlight lang="min">args</syntaxhighlight> |
||
=={{header|MMIX}}== |
=={{header|MMIX}}== |
||
< |
<syntaxhighlight lang="mmix">argv IS $1 |
||
argc IS $0 |
argc IS $0 |
||
i IS $2 |
i IS $2 |
||
Line 1,261: | Line 1,700: | ||
TRAP 0,Halt,0 |
TRAP 0,Halt,0 |
||
NewLine BYTE #a,0</ |
NewLine BYTE #a,0</syntaxhighlight> |
||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE try; |
||
FROM Arguments IMPORT GetArgs, ArgTable, GetEnv; |
FROM Arguments IMPORT GetArgs, ArgTable, GetEnv; |
||
Line 1,283: | Line 1,722: | ||
INC (item) |
INC (item) |
||
UNTIL item = count |
UNTIL item = count |
||
END try.</ |
END try.</syntaxhighlight> |
||
Example: |
Example: |
||
<syntaxhighlight lang="modula-2"> |
|||
<lang Modula-2> |
|||
jan@Beryllium:~/modula/test$ try jantje zag eens pruimen hangen |
jan@Beryllium:~/modula/test$ try jantje zag eens pruimen hangen |
||
Count = 6 |
Count = 6 |
||
Line 1,294: | Line 1,733: | ||
4 : pruimen |
4 : pruimen |
||
5 : hangen |
5 : hangen |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
Command line parameters are accessed using the <tt>Params</tt> module. |
Command line parameters are accessed using the <tt>Params</tt> module. |
||
< |
<syntaxhighlight lang="modula3">MODULE Args EXPORTS Main; |
||
IMPORT IO, Params; |
IMPORT IO, Params; |
||
Line 1,309: | Line 1,748: | ||
END; |
END; |
||
END; |
END; |
||
END Args.</ |
END Args.</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,323: | Line 1,762: | ||
20 |
20 |
||
</pre> |
</pre> |
||
=={{header|Nanoquery}}== |
|||
{{trans|Ursa}} |
|||
<syntaxhighlight lang="nanoquery">// |
|||
// command-line arguments |
|||
// |
|||
// output all arguments |
|||
for i in range(0, len(args) - 1) |
|||
println args[i] |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ java -jar ../nanoquery-2.3_1700.jar -b cmdline.nq "alpha beta" -h "gamma" |
|||
-b |
|||
cmdline.nq |
|||
alpha beta |
|||
-h |
|||
gamma</pre> |
|||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
< |
<syntaxhighlight lang="actionscript">/* command line arguments, neko */ |
||
var argc = $asize($loader.args) |
var argc = $asize($loader.args) |
||
Line 1,332: | Line 1,789: | ||
var arg = 0 |
var arg = 0 |
||
while arg < argc $print($loader.args[arg ++= 1], "\n")</ |
while arg < argc $print($loader.args[arg ++= 1], "\n")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,344: | Line 1,801: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
Line 1,357: | Line 1,814: | ||
foreach (cl_arg in cl_args) Write($"$cl_arg "); |
foreach (cl_arg in cl_args) Write($"$cl_arg "); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
In a stand-alone application NetRexx places the command string passed to it in a variable called <tt>arg</tt>. |
In a stand-alone application NetRexx places the command string passed to it in a variable called <tt>arg</tt>. |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
-- sample arguments: -c "alpha beta" -h "gamma" |
-- sample arguments: -c "alpha beta" -h "gamma" |
||
say "program arguments:" arg |
say "program arguments:" arg |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Output:''' |
'''Output:''' |
||
<pre> |
<pre> |
||
Line 1,371: | Line 1,828: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import os |
||
echo "program name: ", getAppFilename() |
|||
echo "Arguments:" |
|||
let arguments = commandLineParams()</lang> |
|||
for arg in commandLineParams(): |
|||
echo arg</syntaxhighlight> |
|||
=={{header|Nu}}== |
|||
In Nu, the special <code>main</code> function can be declared, which gets passed the cli arguments. |
|||
<syntaxhighlight lang="nu"> |
|||
def main [...argv] { |
|||
$argv | print |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
~> nu cli.nu A B C "Hello World!" |
|||
╭───┬──────────────╮ |
|||
│ 0 │ A │ |
|||
│ 1 │ B │ |
|||
│ 2 │ C │ |
|||
│ 3 │ Hello World! │ |
|||
╰───┴──────────────╯ |
|||
</pre> |
|||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{works with|oo2c}} |
{{works with|oo2c}} |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE CommandLineArguments; |
MODULE CommandLineArguments; |
||
IMPORT |
IMPORT |
||
Line 1,391: | Line 1,868: | ||
Out.String("4.-: ");Out.String(Args.AsString(4));Out.Ln |
Out.String("4.-: ");Out.String(Args.AsString(4));Out.Ln |
||
END CommandLineArguments. |
END CommandLineArguments. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,403: | Line 1,880: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
class Line { |
|||
bundle Default { |
|||
function : Main(args : String[]) ~ Nil { |
|||
class Line { |
|||
each(i : args) { |
|||
args[i]->PrintLine(); |
|||
}; |
|||
args[i]->PrintLine(); |
|||
}; |
|||
} |
|||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|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: |
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: |
||
< |
<syntaxhighlight lang="objc">NSArray *args = [[NSProcessInfo processInfo] arguments]; |
||
NSLog(@"This program is named %@.", [args objectAtIndex:0]); |
NSLog(@"This program is named %@.", [args objectAtIndex:0]); |
||
NSLog(@"There are %d arguments.", [args count] - 1); |
NSLog(@"There are %d arguments.", [args count] - 1); |
||
for (i = 1; i < [args count]; ++i){ |
for (i = 1; i < [args count]; ++i){ |
||
NSLog(@"the argument #%d is %@", i, [args objectAtIndex:i]); |
NSLog(@"the argument #%d is %@", i, [args objectAtIndex:i]); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Line 1,429: | Line 1,904: | ||
The program name is also passed as "argument", so the array length is actually one more than the number of program arguments. |
The program name is also passed as "argument", so the array length is actually one more than the number of program arguments. |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
Printf.printf "This program is named %s.\n" Sys.argv.(0); |
Printf.printf "This program is named %s.\n" Sys.argv.(0); |
||
for i = 1 to Array.length Sys.argv - 1 do |
for i = 1 to Array.length Sys.argv - 1 do |
||
Printf.printf "the argument #%d is %s\n" i Sys.argv.(i) |
Printf.printf "the argument #%d is %s\n" i Sys.argv.(i) |
||
done</ |
done</syntaxhighlight> |
||
=== Using the [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Arg.html Arg] module === |
|||
=== Using the [https://ocaml.org/api/Arg.html Arg] module === |
|||
<lang ocaml>(* default values *) |
|||
<syntaxhighlight lang="ocaml">(* default values *) |
|||
let somebool = ref false |
let somebool = ref false |
||
let somestr = ref "" |
let somestr = ref "" |
||
Line 1,456: | Line 1,930: | ||
(fun x -> raise (Arg.Bad ("Bad argument : " ^ x))) |
(fun x -> raise (Arg.Bad ("Bad argument : " ^ x))) |
||
usage; |
usage; |
||
Printf.printf " %b %d '%s'\n" !somebool !someint !somestr</syntaxhighlight> |
|||
<pre> |
|||
$ ocaml arg.ml --help |
|||
usage: arg.ml [-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 |
|||
--help Display this list of options |
|||
$ ocaml arg.ml -d 4 -b -s blabla |
|||
Printf.printf " %b %d '%s'\n" !somebool !someint !somestr; |
|||
true 4 'blabla' |
|||
;;</lang> |
|||
$ ocaml arg.ml |
|||
false 0 '' |
|||
</pre> |
|||
=={{header|Odin}}== |
|||
% ocaml arg.ml --help |
|||
usage: tmp.ml [-b] [-s string] [-d int] |
|||
<syntaxhighlight lang="odin">package main |
|||
-b : set somebool to true |
|||
-s : what follows -s sets some string |
|||
import "core:os" |
|||
-d : some int parameter |
|||
import "core:fmt" |
|||
--help Display this list of options |
|||
main :: proc() { |
|||
% ocaml arg.ml -d 4 -b -s blabla |
|||
fmt.println(os.args) |
|||
true 4 'blabla' |
|||
} |
|||
% ocaml arg.ml |
|||
false 0 <nowiki>''</nowiki> |
|||
// Run: ./program -c "alpha beta" -h "gamma" |
|||
// Output: ["./program", "-c", "alpha beta", "-h", "gamma"] |
|||
</syntaxhighlight> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 1,482: | Line 1,969: | ||
The first argument is the program name, so this list is never empty. |
The first argument is the program name, so this list is never empty. |
||
<lang |
<syntaxhighlight lang="oforth">System.Args println</syntaxhighlight> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
===Raw arguments=== |
===Raw arguments=== |
||
Like in C, but without the program name: |
Like in C, but without the program name: |
||
< |
<syntaxhighlight lang="oz">functor |
||
import Application System |
import Application System |
||
define |
define |
||
Line 1,493: | Line 1,980: | ||
{ForAll ArgList System.showInfo} |
{ForAll ArgList System.showInfo} |
||
{Application.exit 0} |
{Application.exit 0} |
||
end</ |
end</syntaxhighlight> |
||
===Preprocessed arguments=== |
===Preprocessed arguments=== |
||
< |
<syntaxhighlight lang="oz">functor |
||
import Application System |
import Application System |
||
define |
define |
||
Line 1,512: | Line 1,999: | ||
{System.showInfo Args.h} |
{System.showInfo Args.h} |
||
{Application.exit 0} |
{Application.exit 0} |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
==={{header|Free Pascal}}=== |
|||
Depends on implementation. |
|||
<syntaxhighlight lang="pascal"> |
|||
Program listArguments(input, output, stdErr); |
|||
Var |
|||
i: integer; |
|||
Begin |
|||
writeLn('program was called from: ',paramStr(0)); |
|||
For i := 1 To paramCount() Do |
|||
Begin |
|||
writeLn('argument',i:2,' : ', paramStr(i)); |
|||
End; |
|||
End. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
./Commandlinearguments -c "alpha beta" -h "gamma" |
|||
program was called from: /home/user/Documents/GitHub/rosettacode/Commandlinearguments |
|||
argument 1 : -c |
|||
argument 2 : alpha beta |
|||
argument 3 : -h |
|||
argument 4 : gamma |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Line 1,521: | Line 2,031: | ||
@ARGV is the array containing all command line parameters |
@ARGV is the array containing all command line parameters |
||
< |
<syntaxhighlight lang="perl">my @params = @ARGV; |
||
my $params_size = @ARGV; |
my $params_size = @ARGV; |
||
my $second = $ARGV[1]; |
my $second = $ARGV[1]; |
||
my $fifth = $ARGV[4];</ |
my $fifth = $ARGV[4];</syntaxhighlight> |
||
If you don't mind importing a module: |
If you don't mind importing a module: |
||
< |
<syntaxhighlight lang="perl">use Getopt::Long; |
||
GetOptions ( |
GetOptions ( |
||
'help|h' => \my $help, |
'help|h' => \my $help, |
||
'verbose|v' => \my $verbose, |
'verbose|v' => \my $verbose, |
||
);</ |
);</syntaxhighlight> |
||
=={{header|Perl 6}}== |
|||
Perl 5's <code>@ARGV</code> is available as <code>@*ARGS</code>. Alternatively, if you define a subroutine named <code>MAIN</code>, Perl will automatically process <code>@*ARGS</code> according to Unix conventions and <code>MAIN</code>'s signature (or signatures, if your <code>MAIN</code> is a multi sub) and then call <code>MAIN</code> with appropriate arguments; see [http://perlcabal.org/syn/S06.html#Declaring_a_MAIN_subroutine Synopsis 6] or [http://perlgeek.de/en/article/5-to-6#post_14|5-to-6]. |
|||
<lang perl6># with arguments supplied |
|||
$ perl6 -e 'sub MAIN($x, $y) { say $x + $y }' 3 5 |
|||
8 |
|||
# missing argument: |
|||
$ perl6 -e 'sub MAIN($x, $y) { say $x + $y }' 3 |
|||
Usage: |
|||
-e '...' x y</lang> |
|||
If the program is stored in a file, the file name is printed instead of <code>-e '...'</code>. |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<lang Phix>constant cmd = command_line() |
|||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
|||
?cmd |
|||
<span style="color: #008080;">constant</span> <span style="color: #000000;">cmd</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">command_line</span><span style="color: #0000FF;">()</span> |
|||
if cmd[1]=cmd[2] then |
|||
<span style="color: #0000FF;">?</span><span style="color: #000000;">cmd</span> |
|||
printf(1,"Compiled executable name: %s\n",{cmd[1]}) |
|||
<span style="color: #008080;">if</span> <span style="color: #000000;">cmd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> |
|||
else |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Compiled executable name: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]})</span> |
|||
printf(1,"Interpreted (using %s) source name: %s\n",cmd[1..2]) |
|||
<span style="color: #008080;">else</span> |
|||
end if |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Interpreted (using %s) source name: %s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span> |
|||
if length(cmd)>2 then |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
puts(1,"Command line arguments:\n") |
|||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">)></span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> |
|||
for i = 3 to length(cmd) do |
|||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Command line arguments:\n"</span><span style="color: #0000FF;">)</span> |
|||
printf(1,"#%d : %s\n",{i,cmd[i]}) |
|||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> |
|||
end for |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"#%d : %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">cmd</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]})</span> |
|||
end if</lang> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<!--</syntaxhighlight>--> |
|||
When interpreting, the first two elements returned by command_line() are {interpreter,source}.<br> |
When interpreting, the first two elements returned by command_line() are {interpreter,source}.<br> |
||
When compiled, the first two elements are instead {executable,executable}, so the parameters (if any) are consistently the 3rd element onwards. |
When compiled, the first two elements are instead {executable,executable}, so the parameters (if any) are consistently the 3rd element onwards. |
||
{{out}} |
{{out}} |
||
desktop/Phix (Windows, Linux would be fairly similar but obviously with different paths): |
|||
<pre> |
<pre> |
||
C:\Program Files (x86)\Phix>p testcl -c "alpha beta" -h "gamma" |
C:\Program Files (x86)\Phix>p testcl -c "alpha beta" -h "gamma" |
||
Line 1,591: | Line 2,091: | ||
#6 : gamma |
#6 : gamma |
||
C:\Program Files (x86)\Phix> |
C:\Program Files (x86)\Phix> |
||
</pre> |
|||
pwa/p2js: There isn't really a command line, you always get a result of length 2. |
|||
<pre> |
|||
{"p2js","file:///C:/Program%20Files%20(x86)/Phix/pwa/test.htm"} |
|||
Interpreted (using p2js) source name: file:///C:/Program%20Files%20(x86)/Phix/pwa/test.htm |
|||
</pre> |
</pre> |
||
Line 1,596: | Line 2,101: | ||
When PHP is run from the command line, the special variables <tt>$argv</tt> and <tt>$argc</tt> contain the array of arguments, and the number of arguments, respectively. The program name is passed as the first argument. |
When PHP is run from the command line, the special variables <tt>$argv</tt> and <tt>$argc</tt> contain the array of arguments, and the number of arguments, respectively. The program name is passed as the first argument. |
||
< |
<syntaxhighlight lang="php"><?php |
||
$program_name = $argv[0]; |
$program_name = $argv[0]; |
||
$second_arg = $argv[2]; |
$second_arg = $argv[2]; |
||
$all_args_without_program_name = array_shift($argv); |
$all_args_without_program_name = array_shift($argv); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Picat}}== |
|||
Picat has no built-in option parser, and the user must write a specific parser for each use case. The arguments to a Picat programs are available via <code>main/1</code> as a list of strings. |
|||
<syntaxhighlight lang="picat">main(ARGS) => |
|||
println(ARGS). |
|||
main(_) => true.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>picat command_line_arguments.pi -c "alpha beta" -h "gamma" |
|||
[-c,alpha beta,-h,gamma]</pre> |
|||
See the task [http://rosettacode.org/wiki/Command-line_arguments Command-line_arguments] for a simple option parser. |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
Line 1,617: | Line 2,135: | ||
and then '[http://software-lab.de/doc/refL.html#load load]' all remaining |
and then '[http://software-lab.de/doc/refL.html#load load]' all remaining |
||
command line arguments. |
command line arguments. |
||
< |
<syntaxhighlight lang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l |
||
(de c () |
(de c () |
||
Line 1,626: | Line 2,144: | ||
(load T) |
(load T) |
||
(bye)</ |
(bye)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>$ ./myprogram -c "alpha beta" -h "gamma" |
<pre>$ ./myprogram -c "alpha beta" -h "gamma" |
||
Line 1,633: | Line 2,151: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli"> |
||
/* The entire command line except the command word itself is passed */ |
/* The entire command line except the command word itself is passed */ |
||
/* to the parameter variable in PL/I. */ |
/* to the parameter variable in PL/I. */ |
||
Line 1,642: | Line 2,160: | ||
end program; |
end program; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
Line 1,648: | Line 2,166: | ||
variable poparglist contains list of command line arguments (as strings). One can use iteration over list to process then (for example print). |
variable poparglist contains list of command line arguments (as strings). One can use iteration over list to process then (for example print). |
||
< |
<syntaxhighlight lang="pop11">lvars arg; |
||
for arg in poparglist do |
for arg in poparglist do |
||
printf(arg, '->%s<-\n'); |
printf(arg, '->%s<-\n'); |
||
endfor;</ |
endfor;</syntaxhighlight> |
||
=={{header|PowerBASIC}}== |
=={{header|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 [[#BASIC|QuickBASIC]] above: |
For versions of PowerBASIC prior to [[PB/Win]] 9 and [[PB/CC]] 5, the only option available is identical to the one used by [[#BASIC|QuickBASIC]] above: |
||
< |
<syntaxhighlight lang="powerbasic">? "args: '"; COMMAND$; "'"</syntaxhighlight> |
||
Current versions of PowerBASIC (with the likely exception of [[PB/DOS]]) include <code>COMMAND$()</code> that works similarly to [[FreeBASIC]]'s <code>COMMAND$()</code>, except that you can't retrieve the application's name: |
Current versions of PowerBASIC (with the likely exception of [[PB/DOS]]) include <code>COMMAND$()</code> that works similarly to [[FreeBASIC]]'s <code>COMMAND$()</code>, except that you can't retrieve the application's name: |
||
< |
<syntaxhighlight lang="powerbasic">'these two both return ALL args |
||
? COMMAND$ |
? COMMAND$ |
||
? COMMAND$(0) |
? COMMAND$(0) |
||
Line 1,665: | Line 2,183: | ||
PRINT "The argument "; i; " is "; COMMAND$(i) |
PRINT "The argument "; i; " is "; COMMAND$(i) |
||
i = i + 1 |
i = i + 1 |
||
LOOP</ |
LOOP</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
In PowerShell the arguments to a script can be accessed with the <code>$args</code> array: |
In PowerShell the arguments to a script can be accessed with the <code>$args</code> array: |
||
< |
<syntaxhighlight lang="powershell">$i = 0 |
||
foreach ($s in $args) { |
foreach ($s in $args) { |
||
Write-Host Argument (++$i) is $s |
Write-Host Argument (++$i) is $s |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Prolog}}== |
|||
The command line arguments supplied to a Prolog interpreter can be accessed by passing <code>os_argv</code> to <code>current_prolog_flag/2</code>. |
|||
<syntaxhighlight lang="prolog">:- |
|||
current_prolog_flag(os_argv, Args), |
|||
write(Args).</syntaxhighlight> |
|||
Alternatively, <code>argv</code> can be used to access only the arguments *not* consumed by the Prolog interpreter. |
|||
<syntaxhighlight lang="prolog">:- |
|||
current_prolog_flag(argv, Args), |
|||
write(Args).</syntaxhighlight> |
|||
This omits the interpreter name, the input Prolog filename, and any other arguments directed at the Prolog interpreter. |
|||
=={{header|Pure}}== |
=={{header|Pure}}== |
||
Arguments are in global variables, argc and argv. |
Arguments are in global variables, argc and argv. |
||
< |
<syntaxhighlight lang="pure"> |
||
using system; |
using system; |
||
printf "There are %d command line argumants\n" argc; |
printf "There are %d command line argumants\n" argc; |
||
puts "They are " $$ map (puts) argv; |
puts "They are " $$ map (puts) argv; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Line 1,688: | Line 2,219: | ||
===Reading all parameters=== |
===Reading all parameters=== |
||
You can easily read all parameters by using ProgramParameter() without argument. |
You can easily read all parameters by using ProgramParameter() without argument. |
||
< |
<syntaxhighlight lang="purebasic">If OpenConsole() |
||
Define n=CountProgramParameters() |
Define n=CountProgramParameters() |
||
PrintN("Reading all parameters") |
PrintN("Reading all parameters") |
||
Line 1,698: | Line 2,229: | ||
Input() |
Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
===Reading specific parameters=== |
===Reading specific parameters=== |
||
You can specify which parameter 'n' to read. |
You can specify which parameter 'n' to read. |
||
< |
<syntaxhighlight lang="purebasic">If OpenConsole() |
||
Define n |
Define n |
||
PrintN("Reading specific pameters") |
PrintN("Reading specific pameters") |
||
Line 1,710: | Line 2,241: | ||
Input() |
Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|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: |
''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: |
||
< |
<syntaxhighlight lang="python">import sys |
||
program_name = sys.argv[0] |
program_name = sys.argv[0] |
||
arguments = sys.argv[1:] |
arguments = sys.argv[1:] |
||
count = len(arguments)</ |
count = len(arguments)</syntaxhighlight> |
||
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). |
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). |
||
Line 1,730: | Line 2,261: | ||
Suppose you want to call your script <tt>test.r</tt> with the arguments <tt>a=1 b=c(2,5,6)</tt>, where <tt>b</tt> is a numeric vector. Suppose you also want to redirect your output to <tt>test.out</tt> (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 |
Suppose you want to call your script <tt>test.r</tt> with the arguments <tt>a=1 b=c(2,5,6)</tt>, where <tt>b</tt> is a numeric vector. Suppose you also want to redirect your output to <tt>test.out</tt> (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 |
||
< |
<syntaxhighlight lang="r">R CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out</syntaxhighlight> |
||
from the commandline, with the following text in <tt>test.r</tt>: |
from the commandline, with the following text in <tt>test.r</tt>: |
||
< |
<syntaxhighlight lang="r"># Read the commandline arguments |
||
args <- (commandArgs(TRUE)) |
args <- (commandArgs(TRUE)) |
||
Line 1,751: | Line 2,282: | ||
} |
} |
||
print(a*2) |
print(a*2) |
||
print(b*3)</ |
print(b*3)</syntaxhighlight> |
||
(possibly preceding code that actually does something :-) Your output <tt>test.out</tt> would then contain (e.g., if you <tt>cat</tt> it) |
(possibly preceding code that actually does something :-) Your output <tt>test.out</tt> would then contain (e.g., if you <tt>cat</tt> it) |
||
Line 1,773: | Line 2,304: | ||
The following is the simplest program that prints the command-line arguments: |
The following is the simplest program that prints the command-line arguments: |
||
< |
<syntaxhighlight lang="scheme">#lang racket |
||
(current-command-line-arguments)</ |
(current-command-line-arguments)</syntaxhighlight> |
||
You can also explicitly print each argument to standard output: |
You can also explicitly print each argument to standard output: |
||
< |
<syntaxhighlight lang="scheme">#lang racket |
||
(for ([arg (current-command-line-arguments)]) (displayln arg))</ |
(for ([arg (current-command-line-arguments)]) (displayln arg))</syntaxhighlight> |
||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
Perl 5's <code>@ARGV</code> is available as <code>@*ARGS</code>. Alternatively, if you define a subroutine named <code>MAIN</code>, Perl will automatically process <code>@*ARGS</code> according to Unix conventions and <code>MAIN</code>'s signature (or signatures, if your <code>MAIN</code> is a multi sub) and then call <code>MAIN</code> with appropriate arguments; for more detailed information see: https://docs.raku.org/language/create-cli |
|||
<syntaxhighlight lang="raku" line># with arguments supplied |
|||
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5 |
|||
8 |
|||
# missing argument: |
|||
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 |
|||
Usage: |
|||
-e '...' x y</syntaxhighlight> |
|||
If the program is stored in a file, the file name is printed instead of <code>-e '...'</code>. |
|||
=={{header|RapidQ}}== |
=={{header|RapidQ}}== |
||
< |
<syntaxhighlight lang="rapidq">PRINT "This program is named "; Command$(0) |
||
FOR i=1 TO CommandCount |
FOR i=1 TO CommandCount |
||
PRINT "The argument "; i; " is "; Command$(i) |
PRINT "The argument "; i; " is "; Command$(i) |
||
NEXT i</ |
NEXT i</syntaxhighlight> |
||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven">ARGS print |
||
stack (6 items) |
stack (6 items) |
||
Line 1,798: | Line 2,344: | ||
3 => "alpha beta" |
3 => "alpha beta" |
||
4 => "-h" |
4 => "-h" |
||
5 => "gamma"</ |
5 => "gamma"</syntaxhighlight> |
||
=={{header|REALbasic}}== |
=={{header|REALbasic}}== |
||
< |
<syntaxhighlight lang="vb">Function Run(args() as String) As Integer |
||
For each arg As String In args |
For each arg As String In args |
||
Stdout.WriteLine(arg) |
Stdout.WriteLine(arg) |
||
Next |
Next |
||
End Function</ |
End Function</syntaxhighlight> |
||
Output (given arguments: ''--foo !bar "bat bang"''): |
Output (given arguments: ''--foo !bar "bat bang"''): |
||
appName.exe |
appName.exe |
||
Line 1,814: | Line 2,360: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
The entire command line arguments (as a single string) are passed by REXX to the program. |
The entire command line arguments (as a single string) are passed by REXX to the program. |
||
< |
<syntaxhighlight lang="rexx">say 'command arguments:' |
||
say arg(1)</ |
say arg(1)</syntaxhighlight> |
||
Input: |
Input: |
||
Line 1,823: | Line 2,369: | ||
only options that start with a minus (-) are to be examined |
only options that start with a minus (-) are to be examined |
||
and assumed to be options. |
and assumed to be options. |
||
< |
<syntaxhighlight lang="rexx">parse arg aaa /*get the arguments. */ |
||
/*another version: */ |
/*another version: */ |
||
/* aaa=arg(1) */ |
/* aaa=arg(1) */ |
||
Line 1,844: | Line 2,390: | ||
say |
say |
||
say 'options='opts |
say 'options='opts |
||
say ' data='data</ |
say ' data='data</syntaxhighlight> |
||
;Note to users of Microsoft Windows and Regina REXX: |
;Note to users of Microsoft Windows and Regina REXX: |
||
Line 1,907: | Line 2,453: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
see copy("=",30) + nl |
see copy("=",30) + nl |
||
see "Command Line Parameters" + nl |
see "Command Line Parameters" + nl |
||
Line 1,916: | Line 2,462: | ||
see x + nl |
see x + nl |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
Line 1,922: | Line 2,468: | ||
myprog: |
myprog: |
||
< |
<syntaxhighlight lang="ruby">#! /usr/bin/env ruby |
||
p ARGV</ |
p ARGV</syntaxhighlight> |
||
myprog a -h b c |
myprog a -h b c |
||
Line 1,929: | Line 2,475: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">use std::env; |
||
fn main(){ |
fn main(){ |
||
let args: Vec<_> = env::args().collect(); |
let args: Vec<_> = env::args().collect(); |
||
println!("{:?}", args); |
println!("{:?}", args); |
||
}</ |
}</syntaxhighlight> |
||
Run: |
Run: |
||
<lang>./program -c "alpha beta" -h "gamma" |
<syntaxhighlight lang="text">./program -c "alpha beta" -h "gamma" |
||
["./program", "-c", "alpha beta", "-h", "gamma"]</ |
["./program", "-c", "alpha beta", "-h", "gamma"]</syntaxhighlight> |
||
=={{header|S-lang}}== |
=={{header|S-lang}}== |
||
The command-line arguments exist in the array __argv: |
The command-line arguments exist in the array __argv: |
||
< |
<syntaxhighlight lang="s-lang">variable a; |
||
foreach a (__argv) |
foreach a (__argv) |
||
print(a); |
print(a); |
||
</ |
</syntaxhighlight>Note 1: This array can be changed by calling |
||
__set_argc_argv(new_argv); |
__set_argc_argv(new_argv); |
||
Line 1,960: | Line 2,506: | ||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
main(args:ARRAY{STR}) is |
main(args:ARRAY{STR}) is |
||
loop |
loop |
||
Line 1,966: | Line 2,512: | ||
end; |
end; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
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. |
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. |
||
Line 1,985: | Line 2,531: | ||
array of strings, and returns unit. That array contains the command line arguments. |
array of strings, and returns unit. That array contains the command line arguments. |
||
< |
<syntaxhighlight lang="scala">object CommandLineArguments extends App { |
||
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}") |
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}") |
||
}</ |
}</syntaxhighlight> |
||
When running a Scala script, where the whole body is executed, the arguments get stored in an array of strings called <code>argv</code>: |
When running a Scala script, where the whole body is executed, the arguments get stored in an array of strings called <code>argv</code>: |
||
< |
<syntaxhighlight lang="scala">println(s"Received the following arguments: + ${argv.mkString("", ", ", ".")}")</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme"> (define (main args) |
||
(for-each (lambda (arg) (display arg) (newline)) args))</ |
(for-each (lambda (arg) (display arg) (newline)) args))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 2,010: | Line 2,556: | ||
writeln("The argument #" <& i <& " is " <& argv(PROGRAM)[i]); |
writeln("The argument #" <& i <& " is " <& argv(PROGRAM)[i]); |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Command line arguments are available in the ARGV array. |
Command line arguments are available in the ARGV array. |
||
<lang |
<syntaxhighlight lang="ruby">say ARGV;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>% myprog -c "alpha beta" -h "gamma" |
<pre>% myprog -c "alpha beta" -h "gamma" |
||
Line 2,021: | Line 2,567: | ||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">StartupArguments do: [| :arg | inform: arg]</syntaxhighlight> |
||
=={{header|Slope}}== |
|||
Command line arguments are available in the '''sys-args''' list. |
|||
<syntaxhighlight lang="slope">(display sys-args)</syntaxhighlight> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|GNU Smalltalk}} |
{{works with|GNU Smalltalk}} |
||
< |
<syntaxhighlight lang="smalltalk">(1 to: Smalltalk getArgc) do: [ :i | |
||
(Smalltalk getArgv: i) displayNl |
(Smalltalk getArgv: i) displayNl |
||
]</ |
]</syntaxhighlight> |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
<lang |
<syntaxhighlight lang="smalltalk">Smalltalk commandLineArguments printCR. |
||
Smalltalk commandLineArguments do:[:each | each printCR]</syntaxhighlight> |
|||
=={{header|SparForte}}== |
|||
As a structured script. |
|||
<syntaxhighlight lang="ada">#!/usr/local/bin/spar |
|||
pragma annotate( summary, "printargs" ) |
|||
@( description, "Retrieve the list of command-line arguments given to the program." ) |
|||
@( description, "Example command line: " ) |
|||
@( description, "myprogram -c 'alpha beta' -h 'gamma'" ) |
|||
@( category, "tutorials" ) |
|||
@( author, "Ken O. Burtch" ) |
|||
@( see_also, "http://rosettacode.org/wiki/Command-line_arguments" ); |
|||
pragma license( unrestricted ); |
|||
pragma software_model( nonstandard ); |
|||
pragma restriction( no_external_commands ); |
|||
procedure printargs is |
|||
begin |
|||
put_line( "The command is '" & command_line.command_name & "'" ); |
|||
for Arg in 1..command_line.argument_count loop |
|||
put( "Argument" ) @ (Arg ) @ ( " is '" ) @ |
|||
( command_line.argument(Arg) ) @ ("'"); |
|||
new_line; |
|||
end loop; |
|||
end printargs;</syntaxhighlight> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">print ("This program is named " ^ CommandLine.name () ^ ".\n"); |
||
val args = CommandLine.arguments (); |
val args = CommandLine.arguments (); |
||
Array.appi |
Array.appi |
||
(fn (i, x) => print ("the argument #" ^ Int.toString (i+1) ^ " is " ^ x ^ "\n")) |
(fn (i, x) => print ("the argument #" ^ Int.toString (i+1) ^ " is " ^ x ^ "\n")) |
||
(Array.fromList args);</ |
(Array.fromList args);</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">let args = Process.arguments |
||
println("This program is named \(args[0]).") |
println("This program is named \(args[0]).") |
||
println("There are \(args.count-1) arguments.") |
println("There are \(args.count-1) arguments.") |
||
for i in 1..<args.count { |
for i in 1..<args.count { |
||
println("the argument #\(i) is \(args[i])") |
println("the argument #\(i) is \(args[i])") |
||
}</ |
}</syntaxhighlight> |
||
Alternately: |
Alternately: |
||
{{works with|Swift|1.2+}} |
{{works with|Swift|1.2+}} |
||
< |
<syntaxhighlight lang="swift">println("This program is named \(String.fromCString(Process.unsafeArgv[0])!).") |
||
println("There are \(Process.argc-1) arguments.") |
println("There are \(Process.argc-1) arguments.") |
||
for i in 1 ..< Int(Process.argc) { |
for i in 1 ..< Int(Process.argc) { |
||
println("the argument #\(i) is \(String.fromCString(Process.unsafeArgv[i])!)") |
println("the argument #\(i) is \(String.fromCString(Process.unsafeArgv[i])!)") |
||
}</ |
}</syntaxhighlight> |
||
{{works with|Swift|1.0-1.1}} |
{{works with|Swift|1.0-1.1}} |
||
< |
<syntaxhighlight lang="swift">println("This program is named \(String.fromCString(C_ARGV[0])!).") |
||
println("There are \(C_ARGC-1) arguments.") |
println("There are \(C_ARGC-1) arguments.") |
||
for i in 1 ..< Int(C_ARGC) { |
for i in 1 ..< Int(C_ARGC) { |
||
println("the argument #\(i) is \(String.fromCString(C_ARGV[i])!)") |
println("the argument #\(i) is \(String.fromCString(C_ARGV[i])!)") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Tailspin}}== |
|||
<syntaxhighlight lang="tailspin"> |
|||
$ARGS -> !OUT::write |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[-c, alpha beta, -h, gamma] |
|||
</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Line 2,068: | Line 2,653: | ||
The predefined global variable <tt>argc</tt> contains the number of arguments passed to the program after the script being executed, <tt>argv</tt> contains those arguments as a list. (The name of the script is in the <tt>argv0</tt> global variable, and the name of the executable interpreter itself is returned by the command <code>info nameofexecutable</code>.) Retrieving the second argument might look something like this: |
The predefined global variable <tt>argc</tt> contains the number of arguments passed to the program after the script being executed, <tt>argv</tt> contains those arguments as a list. (The name of the script is in the <tt>argv0</tt> global variable, and the name of the executable interpreter itself is returned by the command <code>info nameofexecutable</code>.) Retrieving the second argument might look something like this: |
||
< |
<syntaxhighlight lang="tcl">if { $argc > 1 } { |
||
puts [lindex $argv 1] |
puts [lindex $argv 1] |
||
}</ |
}</syntaxhighlight> |
||
(Tcl counts from zero, thus <tt>[lindex $list 1]</tt> retrieves the second item in the list) |
(Tcl counts from zero, thus <tt>[lindex $list 1]</tt> retrieves the second item in the list) |
||
Line 2,080: | Line 2,665: | ||
number of arguments is provided by #args. |
number of arguments is provided by #args. |
||
< |
<syntaxhighlight lang="toka">[ arglist array.get type cr ] is show-arg |
||
[ dup . char: = emit space ] is #= |
[ dup . char: = emit space ] is #= |
||
1 #args [ i #= show-arg ] countedLoop</ |
1 #args [ i #= show-arg ] countedLoop</syntaxhighlight> |
||
=={{header|Transd}}== |
|||
<syntaxhighlight lang="Scheme">#lang transd |
|||
MainModule: { |
|||
_start: (λ |
|||
(textout "Number of arguments: " @numArgs |
|||
"\nArgument list: " @progArgs) |
|||
) |
|||
}</syntaxhighlight> |
|||
Linux command ('tree3' is the name of Transd interpreter): |
|||
tree3 progname -c "alpha beta" -h "gamma" |
|||
{{out}} |
|||
<pre> |
|||
Number of arguments: 5 |
|||
Argument list: ["progname", "-c", "alpha beta", "-h", "gamma"] |
|||
</pre> |
|||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
Line 2,090: | Line 2,694: | ||
This <code>@(next :args)</code> 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. |
This <code>@(next :args)</code> 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. |
||
< |
<syntaxhighlight lang="txr">@(next :args) |
||
@(collect) |
@(collect) |
||
@arg |
@arg |
||
Line 2,096: | Line 2,700: | ||
@(output) |
@(output) |
||
My args are: {@(rep)@arg, @(last)@arg@(end)} |
My args are: {@(rep)@arg, @(last)@arg@(end)} |
||
@(end)</ |
@(end)</syntaxhighlight> |
||
<pre>$ ./txr args.txr |
<pre>$ ./txr args.txr |
||
Line 2,109: | Line 2,713: | ||
Here is an example program which requires exactly three arguments. Note how <code>ldiff</code> 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. |
Here is an example program which requires exactly three arguments. Note how <code>ldiff</code> 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. |
||
< |
<syntaxhighlight lang="txrlisp">(tree-case *args* |
||
((a b c) (put-line "got three args, thanks!")) |
((a b c) (put-line "got three args, thanks!")) |
||
(else (put-line `usage: @(ldiff *full-args* *args*) <arg1> <arg2> <arg3>`)))</ |
(else (put-line `usage: @(ldiff *full-args* *args*) <arg1> <arg2> <arg3>`)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ txr command-line-args.txr 1 2 |
<pre>$ txr command-line-args.txr 1 2 |
||
Line 2,123: | Line 2,727: | ||
===[[Bourne Shell]]=== |
===[[Bourne Shell]]=== |
||
To retrieve the entire list of arguments: |
To retrieve the entire list of arguments: |
||
< |
<syntaxhighlight lang="bash">WHOLELIST="$@"</syntaxhighlight> |
||
To retrieve the second and fifth arguments: |
To retrieve the second and fifth arguments: |
||
< |
<syntaxhighlight lang="bash">SECOND=$2 |
||
FIFTH=$5</ |
FIFTH=$5</syntaxhighlight> |
||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
In Ursa, all command line arguments (including the program name as invoked) are contained in the string stream args. |
In Ursa, all command line arguments (including the program name as invoked) are contained in the string stream args. |
||
< |
<syntaxhighlight lang="ursa"># |
||
# command-line arguments |
# command-line arguments |
||
# |
# |
||
Line 2,137: | Line 2,741: | ||
for (decl int i) (< i (size args)) (inc i) |
for (decl int i) (< i (size args)) (inc i) |
||
out args<i> endl console |
out args<i> endl console |
||
end for</ |
end for</syntaxhighlight> |
||
Sample shell session in the Bourne shell: |
Sample shell session in the Bourne shell: |
||
Line 2,152: | Line 2,756: | ||
This example application does nothing but display the data |
This example application does nothing but display the data |
||
structure on standard output. |
structure on standard output. |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#executable ('parameterized','') |
#executable ('parameterized','') |
||
clarg = <.file$[contents: --<''>+ _option%LP]>+ ~command.options</ |
clarg = <.file$[contents: --<''>+ _option%LP]>+ ~command.options</syntaxhighlight> |
||
Here is a bash terminal session. |
Here is a bash terminal session. |
||
<pre>$ clarg -c alpha,beta -h gamma --foo=bar,baz |
<pre>$ clarg -c alpha,beta -h gamma --foo=bar,baz |
||
Line 2,177: | Line 2,781: | ||
args.v |
args.v |
||
< |
<syntaxhighlight lang="v">$stack puts |
||
./args.v a b c |
./args.v a b c |
||
=[args.v a b c]</ |
=[args.v a b c]</syntaxhighlight> |
||
=={{header|Visual Basic}}== |
|||
Like [[#BASIC|Qbasic]], Visual Basic returns all of the args in the built-in variable <code>Command$</code>: |
|||
<lang vb>Sub Main |
|||
MsgBox Command$ |
|||
End Sub</lang> |
|||
=={{header|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. |
|||
<lang vbnet>Sub Main(ByVal args As String()) |
|||
For Each token In args |
|||
Console.WriteLine(token) |
|||
Next |
|||
End Sub</lang> |
|||
=={{header|vbScript}}== |
=={{header|vbScript}}== |
||
< |
<syntaxhighlight lang="vbscript"> |
||
'Command line arguments can be accessed all together by |
'Command line arguments can be accessed all together by |
||
Line 2,220: | Line 2,806: | ||
Wscript.Echo "arg=", arg |
Wscript.Echo "arg=", arg |
||
Next |
Next |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Visual Basic}}== |
|||
Like [[#BASIC|Qbasic]], Visual Basic returns all of the args in the built-in variable <code>Command$</code>: |
|||
<syntaxhighlight lang="vb">Sub Main |
|||
MsgBox Command$ |
|||
End Sub</syntaxhighlight> |
|||
=={{header|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. |
|||
<syntaxhighlight lang="vbnet">Sub Main(ByVal args As String()) |
|||
For Each token In args |
|||
Console.WriteLine(token) |
|||
Next |
|||
End Sub</syntaxhighlight> |
|||
=={{header|V (Vlang)}}== |
|||
This assumes that the following script, myscript.v, is run as follows: |
|||
$ v run myscript.v -c "alpha beta" -h "gamma" |
|||
<syntaxhighlight lang="v (vlang)">import os |
|||
fn main() { |
|||
for i, x in os.args[1..] { |
|||
println("the argument #$i is $x") |
|||
} |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
the argument #0 is -c |
|||
the argument #1 is alpha beta |
|||
the argument #2 is -h |
|||
the argument #3 is gamma |
|||
</pre> |
|||
=={{header|Wren}}== |
|||
This assumes that the following script, Command-line_arguments.wren, is run as follows: |
|||
$ wren Command-line_arguments.wren -c "alpha beta" -h "gamma" |
|||
<syntaxhighlight lang="wren">import "os" for Process |
|||
System.print(Process.arguments)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
[-c, alpha beta, -h, gamma] |
|||
</pre> |
|||
=={{header|XPL0}}== |
|||
Characters following the program name are copied into a buffer that is accessible as device 8. |
|||
This displays the example command line with quote marks stripped off. |
|||
<syntaxhighlight lang="xpl0">int C; |
|||
[loop [C:= ChIn(8); |
|||
if C = \EOF\$1A then quit; |
|||
ChOut(0, C); |
|||
]; |
|||
CrLf(0); |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
-c alpha beta -h gamma |
|||
</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
File myprogram.zkl: |
File myprogram.zkl: |
||
< |
<syntaxhighlight lang="zkl">System.argv.println(); |
||
vm.arglist.println();</ |
vm.arglist.println();</syntaxhighlight> |
||
zkl myprogram -c "alpha beta" -h "gamma" |
zkl myprogram -c "alpha beta" -h "gamma" |
||
{{out}} |
{{out}} |
||
Line 2,238: | Line 2,888: | ||
{{omit from|Commodore BASIC}} |
{{omit from|Commodore BASIC}} |
||
{{omit from|dc}} |
{{omit from|dc}} |
||
{{omit from|EasyLang|Programs cannot be executed outside the IDE, not even in a command line.}} |
|||
{{omit from|GUISS}} |
{{omit from|GUISS}} |
||
{{omit from|Lotus 123 Macro Scripting}} |
{{omit from|Lotus 123 Macro Scripting}} |
Latest revision as of 16:57, 3 April 2024
You are encouraged to solve this task according to the task description, using any language you may know.
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"
11l
:argv
is a list containing all command line arguments, including the program name.
:start:
print(‘Program name: ’:argv[0])
print("Arguments:\n":argv[1..].join("\n"))
8080 Assembly
This program runs under CP/M. CP/M includes some very rudimentary argument parsing: it assumes that the first two space-separated arguments are filenames. Apart from that you can get the raw command line, except that all lowercase letters are made uppercase.
If you need any further parsing, the program needs to do that by itself, which led to many people not bothering. (The CP/M assembler in particular is infamous for abusing the file extension to take arguments.) The following program shows everything CP/M gives it.
putch: equ 2 ; CP/M syscall to print character
puts: equ 9 ; CP/M syscall to print $-terminated string
arglen: equ 80h ; Length of argument
argmt: equ 81h ; Argument string
fcb1: equ 5Ch ; FCBs
fcb2: equ 6Ch
org 100h
;;; Print all argument(s) as given
lxi d,cmdln ; Print 'Command line: '
mvi c,puts
call 5
lda arglen ; Retrieve the length of the argument
lxi h,argmt ; Pointer to argument string
call plstr
;;; CP/M also assumes that the first two words on the command
;;; line are filenames, and prepares two FCBs with the filenames
;;; in them. If there are no filenames, they will be blank.
lxi d,file1 ; Print the first one
mvi c,puts
call 5
mvi a,11 ; Filenames are 8+3 characters long and padded with
lxi h,fcb1+1 ; spaces
call plstr
lxi d,file2 ; Print the second one
mvi c,puts
call 5
mvi a,11
lxi h,fcb2+1
; ... fall through - on small systems saving bytes is a virtue
;;; This subroutine prints a length-A string in HL.
plstr: ana a ; If A=0, print nothing.
rz
push psw ; Save A and HL registers on the stack
push h ; (CP/M syscalls clobber all registers)
mov e,m ; Print character under HL
mvi c,putch
call 5
pop h ; Restore A and HL registers
pop psw
inx h ; Increment string pointer
dcr a ; Decrement character counter
jnz plstr ; Print next character if not zero
ret
cmdln: db 'Command line: $'
file1: db 13,10,'File 1: $'
file2: db 13,10,'File 2: $'
- Output:
A>args A>args Command line: File 1: File 2: A>args -c "alpha beta" -h "gamma" Command line: -C "ALPHA BETA" -H "GAMMA" File 1: -C File 2: "ALPHA A>args foobar.baz barbaz.qux Command line: FOOBAR.BAZ BARBAZ.QUX File 1: FOOBAR BAZ File 2: BARBAZ QUX
8086 Assembly
The method for doing this depends on the memory model of your program. For a COM file, everything is contained in one segment, including the command line arguments. The program starts at offset 100h and the command line arguments start at 81h. It's as simple as reading from that memory address.
For an EXE file, both the DS
and ES
registers are set to the program segment prefix as soon as the program begins. You'll need to load from offset 81h to FFh to get the command line arguments.
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program commandLine64.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/************************************/
/* Initialized data */
/************************************/
.data
szCarriageReturn: .asciz "\n"
/************************************/
/* UnInitialized data */
/************************************/
.bss
.align 4
/************************************/
/* code section */
/************************************/
.text
.global main
main: // entry of program
mov fp,sp // fp <- start address
ldr x4,[fp] // number of Command line arguments
add x5,fp,#8 // first parameter address
mov x2,#0 // init loop counter
1:
ldr x0,[x5,x2,lsl #3] // string address parameter
bl affichageMess // display string
ldr x0,qAdrszCarriageReturn
bl affichageMess // display carriage return
add x2,x2,#1 // increment counter
cmp x2,x4 // number parameters ?
blt 1b // loop
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
- Output:
~/.../rosetta/asm4 $ commandLine64 toto tutu commandLine64 toto tutu
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
begin
-- 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;
New_Line;
end Print_Commands;
Alternative version using Matreshka
Uses Matreshka
with Ada.Wide_Wide_Text_IO;
with League.Application;
with League.Strings;
procedure Main is
begin
for J in 1 .. League.Application.Arguments.Length loop
Ada.Wide_Wide_Text_IO.Put_Line
(League.Application.Arguments.Element (J).To_Wide_Wide_String);
end loop;
end Main;
Aikido
The arguments are passed to the program as a vector of strings called args
foreach arg in args {
println ("arg: " + arg)
}
Aime
integer i;
i = 0;
while (i < argc()) {
o_text(argv(i));
o_byte('\n');
i += 1;
}
ALGOL 68
main:(
FOR i TO argc DO
printf(($"the argument #"g(-0)" is "gl$, i, argv(i)))
OD
)
Linux command:
/usr/bin/a68g Command-line_arguments.a68 - 1 2 3 ...
Output:
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 ...
Amazing Hopper
The main function "main(argv,argc)" is a macro-defined in HOPPER.H: get the arguments, and put them into array ARGV; ARGC have total arguments.
Macro MAIN(ARGV, ARGC):
#defn main(_V_,_N_) #RAND, main:, V#RNDV=1,_V_={#VOID}, \
_N_=0,totalarg,mov(_N_), \
LOOPGETARG_#RNDV:, {[ V#RNDV ]},push(_V_),++V#RNDV,\
{_N_,V#RNDV},jle(LOOPGETARG_#RNDV),clear(V#RNDV)
VERSION 1:
#include <hopper.h>
main(argv, argc)
{"This program named: "},[1]get(argv),println
for(i=2, {i}lethan(argc),++i)
{"Argument #",i," = "}[i]get(argv),println
next
exit(0)
VERSION 2:
#include <hopper.h>
main:
total arg, argc=0,mov(argc)
{"This program named: ",[&1]},println
i=2
__CNT_ARGS__:
{"Argumento #",i," = ",[&i]}println
++i,{argc,i}jle(__CNT_ARGS__)
exit(0)
VERSION 3:
#include <hopper.h>
main(argv, argc)
i=2
#hl{
print( "This program named: ",argv[1],"\n")
while( i <= argc )
print("Argument #",i," = ",argv[i],"\n")
i += 1
wend
}
exit(0)
VERSION 4:
#include <natural.h>
#include <hopper.h>
main:
get total arguments, and remember as 'total arguments'.
remember ("This program named: "),
now remember ( argument '1' ), and print with a new line.
secondly, declare 'i', take '2', and store in 'i'
do while ( variable 'i' is less or equal than 'total arguments', \
consider this ( {"Argument #",i," = "} );\
remember ( argument 'i' ); put a new line and print it; finally increment 'i' ).
exit(0)
ETCETERA...
- Output:
xu@MrDalien:~/Proyectos/xuesp/HOPPER$ hopper src/args1.com 1 "Rosseta code" 100 This program named: src/args1.com Argumento #2 = 1 Argumento #3 = Rosseta code Argumento #4 = 100
AppleScript
#!/usr/bin/env osascript
-- Print first argument
on run argv
return (item 1 of argv)
end run
ARM Assembly
/* ARM assembly Raspberry PI */
/* program commandLine.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szCarriageReturn: .asciz "\n"
/* UnInitialized data */
.bss
.align 4
/* code section */
.text
.global main
main: @ entry of program
push {fp,lr} @ saves registers
add fp,sp,#8 @ fp <- start address
ldr r4,[fp] @ number of Command line arguments
add r5,fp,#4 @ first parameter address
mov r2,#0 @ init loop counter
loop:
ldr r0,[r5,r2,lsl #2] @ string address parameter
bl affichageMess @ display string
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display carriage return
add r2,#1 @ increment counter
cmp r2,r4 @ number parameters ?
blt loop @ loop
100: @ standard end of the program
mov r0, #0 @ return code
pop {fp,lr} @restaur registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur 2 registres
bx lr @ return
Arturo
loop arg 'a [
print a
]
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%
Else
Run, %A_AhkPath% "%A_ScriptFullPath%" -c "\"alpha beta\"" -h "\"gamma\""
AWK
#!/usr/bin/awk -f
BEGIN {
print "There are " ARGC "command line parameters"
for(l=1; l<ARGC; l++) {
print "Argument " l " is " ARGV[l]
}
}
Babel
Invoke Babel in interactive mode with arguments using the -i switch:
babel -i Larry Mo Curly
Print the argv list with newlines:
argv prn !
- Output:
Larry Mo Curly
Print the argv list with spaces:
argv prs !
- Output:
Larry Mo Curly
To access an individual argument, use the ith operator to select an element from the argv list; print with newline using say:
argv 1 ith say !
- Output:
Mo
BASIC
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.'
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
).
DIM i AS INTEGER
PRINT COMMAND$
PRINT "This program is named "; COMMAND$(0)
i = 1
DO WHILE(LEN(COMMAND$(i)))
PRINT "The argument "; i; " is "; COMMAND$(i)
i = i + 1
LOOP
FOR i = 0 TO __FB_ARGC__ - 1
PRINT "arg "; i; " = '"; *__FB_ARGV__[i]; "'"
NEXT 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'
BaCon
' Command line arguments including program name
PRINT "Entire command line: ", ARGUMENT$
SPLIT ARGUMENT$ BY " " TO cli$ SIZE args
PRINT "Skip program name:";
FOR i = 1 TO args - 1
PRINT " " & cli$[i];
NEXT
PRINT
- Output:
prompt$ bacon command-line.bac Converting 'command-line.bac'... done, 9 lines were processed in 0.002 seconds. Compiling 'command-line.bac'... cc -c command-line.bac.c cc -o command-line command-line.bac.o -lbacon -lm Done, program 'command-line' ready. prompt$ ./command-line -c "alpha beta" -h "gamma" Entire command line: ./command-line -c "alpha beta" -h gamma Skip program name: -c "alpha beta" -h gamma
Batch File
@echo off
setlocal enabledelayedexpansion
set Count=0
:loop
if not "%1"=="" (
set /a count+=1
set parameter[!count!]=%1
shift
goto loop
)
for /l %%a in (1,1,%count%) do (
echo !parameter[%%a]!
)
Another way of doing it
::args2.cmd
@echo off
setlocal enabledelayedexpansion
set fn=%~f0
set p0=%~0
set p*=%*
set /a c=1
:loop
if @%1==@ goto done
set p%c%=%~1
set /a c=c+1
shift
goto loop
:done
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!
)
Invocation:
>args2 foo "bar baz" quux
fn=d:\bin\args2.cmd
p0=args2
p*=foo "bar baz" quux
p#=3
p1=foo
p2=bar baz
p3=quux
BBC BASIC
PRINT @cmd$
Blue
Linux/x86-64
global _start
: syscall ( num:eax -- result:eax | rcx ) syscall ;
: exit ( status:edi -- noret ) 60 syscall ;
: bye ( -- noret ) 0 exit ;
: die ( err:eax -- noret ) neg exit ;
: unwrap ( result:eax -- value:eax ) dup 0 cmp ' die xl ;
: ordie ( result -- ) unwrap drop ;
1 const stdout
: write ( buf:esi len:edx fd:edi -- ) 1 syscall ordie ;
: print ( buf len -- ) stdout write ;
: newline ( -- ) s" \n" print ;
: println ( buf len -- ) print newline ;
: find0 ( start:rsi -- end:rsi ) lodsb 0 cmp latest xne ;
: cstrlen ( str:rdi -- len:rsi ) dup find0 swap sub dec ;
: cstr>str ( cstr:rdx -- str:rsi len:rdx ) dup cstrlen xchg ;
: print-arg ( arg -- ) cstr>str println ;
: _start ( rsp -- noret ) dup @ swap
: print-args ( argc:rcx argv:rsp -- noret )
8 add @ print-arg latest loop
bye
;
BQN
BQN has a system value for getting pre-parsed command line arguments.
•Show •args
should show the full list of args.
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)"
Output:
arg[0]=bracmat arg[1]=0:?n&whl'(arg$!n:?a&out$str$(arg[ !n "]=" !a)&1+!n:?n) arg[2]=a arg[3]=/b arg[4]=-c arg[5]=2+3 arg[6]='d;' 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).
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]);
return EXIT_SUCCESS;
}
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]));
}
}
}
C++
Command line arguments are passed the same way as in C.
This example uses <iostream>
. C-style i/o also works.
#include <iostream>
int main(int argc, const char* argv[]) {
std::cout << "This program is named " << argv[0] << '\n'
<< "There are " << argc - 1 << " arguments given.\n";
for (int i = 1; i < argc; ++i)
std::cout << "The argument #" << i << " is " << argv[i] << '\n';
}
C3
Command line arguments are passed to main and will be converted to UTF-8 strings on all platforms.
import std::io;
fn void main(String[] args)
{
io::printfn("This program is named %s.", args[0]);
for (int i = 1; i < args.len; i++)
{
io::printfn("the argument #%d is %s\n", i, args[i]);
}
}
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
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*))
CLU
While it is not part of the language standard as specified in the reference manual,
Portable CLU includes a library function get_argv
which returns
all the arguments in order.
Note that unlike C, the program name itself is not included in the list of arguments.
% This program needs to be merged with PCLU's "useful.lib",
% where get_argv lives.
%
% pclu -merge $CLUHOME/lib/useful.lib -compile cmdline.clu
start_up = proc ()
po: stream := stream$primary_output()
args: sequence[string] := get_argv()
for arg: string in sequence[string]$elements(args) do
stream$putl(po, "arg: " || arg)
end
end start_up
- Output:
$ ./cmdline -c "alpha beta" -h "gamma" arg: -c arg: alpha beta arg: -h arg: gamma
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.
Getting the arguments in one go, exactly as they were passed in:
IDENTIFICATION DIVISION.
PROGRAM-ID. accept-all-args.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 args PIC X(50).
PROCEDURE DIVISION.
main-line.
ACCEPT args FROM COMMAND-LINE
DISPLAY args
GOBACK
.
Getting the arguments one at a time, with arguments being split by whitespace if not in quotes:
IDENTIFICATION DIVISION.
PROGRAM-ID. accept-args-one-at-a-time.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 arg PIC X(50) VALUE SPACES.
PROCEDURE DIVISION.
ACCEPT arg FROM ARGUMENT-VALUE
PERFORM UNTIL arg = SPACES
DISPLAY arg
MOVE SPACES TO arg
ACCEPT arg FROM ARGUMENT-VALUE
END-PERFORM
GOBACK
.
Passing arguments from UNIX/Linux Systems to COBOL.
*>Created By Zwiegnet 8/19/2004
IDENTIFICATION DIVISION.
PROGRAM-ID. arguments.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 command1 PIC X(50).
01 command2 PIC X(50).
01 command3 PIC X(50).
PROCEDURE DIVISION.
PERFORM GET-ARGS.
*> Display Usage for Failed Checks
ARGUSAGE.
display "Usage: <command1> <command2> <command3>"
STOP RUN.
*> Evaluate Arguments
GET-ARGS.
ACCEPT command1 FROM ARGUMENT-VALUE
IF command1 = SPACE OR LOW-VALUES THEN
PERFORM ARGUSAGE
ELSE
INSPECT command1 REPLACING ALL SPACES BY LOW-VALUES
ACCEPT command2 from ARGUMENT-VALUE
IF command2 = SPACE OR LOW-VALUES THEN
PERFORM ARGUSAGE
ELSE
INSPECT command2 REPLACING ALL SPACES BY LOW-VALUES
ACCEPT command3 from ARGUMENT-VALUE
IF command3 = SPACE OR LOW-VALUES THEN
PERFORM ARGUSAGE
ELSE
INSPECT command3 REPLACING ALL SPACES BY LOW-VALUES
*> Display Final Output
display command1 " " command2 " " command3
STOP RUN.
.
CoffeeScript
console.log arg for arg in process.argv
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 ()
(or
#+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*
nil))
Cowgol
Cowgol includes a function to retrieve command-line arguments in its standard library. The manner in which arguments are parsed is, however, dependent on the operating system.
include "cowgol.coh";
include "argv.coh";
ArgvInit();
var i: uint8 := 0;
loop
var arg := ArgvNext();
if arg == 0 as [uint8] then break; end if;
i := i + 1;
print_i8(i);
print(": '");
print(arg);
print("'\n");
end loop;
- Output:
On Linux:
$ ./args -c "alpha beta" -h "gamma" 1: '-c' 2: 'alpha beta' 3: '-h' 4: 'gamma'
On CP/M:
A>args -c "alpha beta" -h "gamma" 1: '-C' 2: '"ALPHA' 3: 'BETA"' 4: '-H' 5: '"GAMMA"'
D
void main(in string[] args) {
import std.stdio;
foreach (immutable i, arg; args[1 .. $])
writefln("#%2d : %s", i + 1, arg);
}
Dart
main(List<String> args) {
for(var arg in args)
print(arg);
}
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
- Output:
$ @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
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
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
- Output:
$ 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. "five"
The order of command line options is lost.
Draco
Draco comes with a library function that will return each command line argument in turn. It simply splits the command line on whitespace, and does not support quotes.
In the example below, the arguments are additionally all made uppercase. This is however a limitation of the CP/M operating system, and not of Draco.
\util.g
proc nonrec main() void:
*char par;
word i;
i := 0;
while par := GetPar(); par ~= nil do
i := i + 1;
writeln(i:3, ": '", par, "'")
od
corp
- Output:
A>param -c "alpha beta" -h "gamma" 1: '-C' 2: '"ALPHA' 3: 'BETA"' 4: '-H' 5: '"GAMMA"'
E
interp.getArgs()
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.
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
make
-- Print values for arguments with options 'c' and 'h'.
do
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
end
end
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
Elena
ELENA 6.x :
import system'routines;
import extensions;
public program()
{
program_arguments.forEvery::(int i)
{ console.printLine("Argument ",i," is ",program_arguments[i]) }
}
- Output:
Argument 0 is myprogram.exe Argument 1 is -c Argument 2 is alpha beta Argument 3 is -h Argument 4 is gamma
Elixir
Elixir provides command line arguments via the System.argv() function.
#!/usr/bin/env elixir
IO.puts 'Arguments:'
Enum.map(System.argv(),&IO.puts(&1))
Example run:
$ ./show-args.exs a b=2 --3 -4
Arguments:
a
b=2
--3
-4
Emacs Lisp
(while argv
(message "Argument: %S" (pop argv)))
Invoke script:
emacs --script test.el foo bar baz
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().
result
[{root,["/usr/erlang/erl5.5"]},
{progname,["erl"]},
{home,["/home/me"]},
{c,["alpha beta"]},
{h,["gamma"]}]
init:get_argument(name) can be used to fetch value of a particular flag
4> init:get_argument(h).
{ok,[["gamma"]]}
5> init:get_argument(c).
{ok,[["alpha beta"]]}
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
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.
#light
[<EntryPoint>]
let main args =
Array.iter (fun x -> printfn "%s" x) args
0
Factor
USING: io sequences command-line ; (command-line) [ print ] each
Fancy
ARGV each: |a| {
a println # print each given command line argument
}
Fantom
class Main
{
public static Void main (Str[] args)
{
echo ("command-line args are: " + args)
}
}
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.
\ 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
gforth
args.f
alpha
beta gamma
delta
$
Fortran
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"
./a.out
-c
alpha beta
-h
gamma
FreeBASIC
' FB 1.05.0 Win64
' Program (myprogram.exe) invoke as follows:
' myprogram -c "alpha beta" -h "gamma"
Print "The program was invoked like this => "; Command(0) + " " + Command(-1)
Print
Print "Press any key to quit"
Sleep
- Output:
The program was invoked like this => myprogram -c alpha beta -h gamma
Frink
Arguments to a program are available in the ARGS
array variable.
println[ARGS]
FunL
println( args )
Gambas
Click this link to run this code
PUBLIC SUB main()
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
NEXT
END
Genie
[indent=4]
/*
Command line arguments, in Genie
valac commandLine.gs
./commandLine sample arguments 'four in total here, including args 0'
*/
init
// Output the number of arguments
print "%d command line argument(s):", args.length
// Enumerate all command line arguments
for s in args
print s
// to reiterate, args[0] is the command
if args[0] is not null
print "\nWith Genie, args[0] is the command: %s", args[0]
- Output:
prompt$ valac commandLine.gs prompt$ ./commandLine -c "alpha beta" -h "gamma" 5 command line argument(s): ./commandLine -c alpha beta -h gamma With Genie, args[0] is the command: ./commandLine
Global Script
Command-line arguments are passed to the main program as a linked list of strings (which are also linked lists).
This uses the gsio
I/O operations, which are designed to be simple to implement on top of Haskell and simple to use. It also uses impmapM, which is a specific specialization of mapM for the HSGS implementation.
λ 'as. impmapM (λ 'a. print qq{Argument: §(a)\n}) as
Go
package main
import (
"fmt"
"os"
)
func main() {
for i, x := range os.Args[1:] {
fmt.Printf("the argument #%d is %s\n", i, x)
}
}
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.
Harbour
Uses the Harbour-specific hb_PValue() function
PROCEDURE Main()
LOCAL i
FOR i := 1 TO PCount()
? "argument", hb_ntos( i ), "=", hb_PValue( i )
NEXT
RETURN
Haskell
Defined by the System module, getArgs :: IO [String] provides the command-line arguments in a list.
myprog.hs:
import System
main = getArgs >>= print
myprog a -h b c => ["a","-h","b","c"]
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
ENDDO
Icon and Unicon
Command line parameters are passed to Icon/Unicon programs as a list of strings.
includes options that parses the command line as switches and arguments and returns the results in a table.
Io
System args foreach(a, a println)
Ioke
System programArguments each(println)
J
The global ARGV
holds the command line arguments. Thus, a program to display them:
ARGV
In a non-interactive context, we would instead use echo ARGV
.
Jakt
The main function can recieve the command line arguments as an arbitrarily named array of String. argv[0] will be the name of the program.
fn main(arguments: [String]) {
println("{}", arguments)
}
Java
The arguments will be passed to main
as the only parameter.
The array is non-null.
public static void main(String[] args)
Running this command
myprogram -c "alpha beta" -h "gamma"
Will produce the following
-c alpha beta -h gamma
And alternate demonstration.
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.
JavaScript
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
var objArgs = WScript.Arguments;
for (var i = 0; i < objArgs.length; i++)
WScript.Echo(objArgs.Item(i));
import System;
var argv:String[] = Environment.GetCommandLineArgs();
for (var i in argv)
print(argv[i]);
for (var i = 0; i < arguments.length; i++)
print(arguments[i]);
Joy
#!/usr/bin/joy
argv rest put.
- Output:
["-c" "alpha beta" "-h" "gamma"]
jq
jq distinguishes between command-line arguments and command-line options.
Only the former are available programmatically.
Specifically, both named and positional command-line arguments are available in the global constant $ARGS, a JSON object, as follows:
$ARGS.positional contains an array of the positional arguments as JSON strings
$ARGS.names is a JSON object of giving the mapping of name to value.
For example, the invocation:
$ jq -n '$ARGS' --args a b
yields:
{
"positional": [
"a",
"b"
],
"named": {}
}
Arguments specified with --args are always read as JSON strings; arguments specified with --jsonargs are interpreted as JSON, as illustrated here:
$ jq -n '$ARGS' --argjson x 0 --jsonargs 0 '{"a":1}' { "positional": [ 0, { "a": 1 } ], "named": { "x": 0 } }
Jsish
#!/usr/local/bin/jsish
puts(Info.argv0());
puts(console.args);
- Output:
$ jsish command-line-arguments.jsi -c "alpha beta" -h "gamma" /home/btiffin/lang/jsish/command-line-arguments.jsi [ "-c", "alpha beta", "-h", "gamma" ]
Julia
Works when the Julia program is run as a file argument to julia.exe.
using Printf
prog = Base.basename(Base.source_path())
println(prog, "'s command-line arguments are:")
for s in ARGS
println(" ", s)
end
- Output:
$ julia command_line_arguments.jl -c "alpha beta" -h "gamma" command_line_arguments.jl's command-line arguments are: -c alpha beta -h gamma
Klong
Command line arguments (but not the program name itself) are bound to the variable ".a". The following program prints them, one argument per line:
.p'.a
Kotlin
fun main(args: Array<String>) {
println("There are " + args.size + " arguments given.")
args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") }
}
- Output:
See Java output.
Lang
In lang command line arguments are stored in &LANG_ARGS.
$ele
foreach($[ele], &LANG_ARGS) {
fn.println($ele)
}
Calling a Lang program with command line arguments depends on the implementation. The following example shows, how this can be achieved in Standard Lang (-- defines the start of the command line arguments for the Lang program):
$ lang cmdarg.lang -- 2 abc test text
- Output:
2 abc test text
Lasso
#!/usr/bin/lasso9
iterate($argv) => {
stdoutnl("Argument " + loop_count + ": " + loop_value)
}
Output:
$ 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
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")))
Liberty BASIC
print CommandLine$
Lingo
put the commandline
-- "-c alpha beta -h gamma"
In latest versions of Mac OS X, the above approach doesn't work anymore. But there is a free "Xtra" (binary plugin/shared library) called "CommandLine Xtra" that works both in Windows and Mac OS X and returns the command-line parsed into a lingo list (array):
put getCommandLineArgs()
-- ["-c", "alpha beta", "-h", "gamma"]
Logo
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
show :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
LSE64
argc , nl # number of arguments (including command itself)
0 # argument
dup arg dup 0 = || ,t 1 + repeat
drop
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] )
end
M2000 Interpreter
function quote$("a") return "a" a string in ""
Arguments in command line maybe two kinds, in first part those three letters identifiers with + or - for switches for interpreter and the last part to executed before loading the actual script.
For this example we make a script, save to temporary directory, and call it passing arguments. We can use Win as shell substitute in M2000 environment, or the Use statement. Reading the shell statement Win we can see how the command line composed. We call the m2000.exe in the appdir$ (application directory, is the path to M2000.exe), and pass a string as a file with a path. That path will be the current path for the new start of m2000.exe the host for M2000 Interpreter (an activeX dll).
Module Checkit {
Document a$ = {
Module Global A {
Show
Read a$="nothing", x=0
Print a$, x
A$=Key$
}
A: End
}
Dir temporary$
Save.doc a$, "program.gsb"
\\ open if gsb extension is register to m2000.exe
Win quote$(dir$+"program.gsb")
\\ +txt is a switch for interpreter to use string comparison as text (not binary)
\\ so we can send switches and commands before the program loading
Win appdir$+"m2000.exe", quote$(dir$+"program.gsb +txt : Data {Hello}, 100")
\\ no coma after name (we can use "program.gsb" for names with spaces)
Use program.gsb "From Use statement", 200
\\ delete file
Wait 5000
Dos "del "+quote$(dir$+"program.gsb");
\\ open directory
Rem : Win temporary$
}
Checkit
Mathematica/Wolfram Language
myprogram:
#!/usr/local/bin/MathematicaScript -script
$CommandLine
Output:
{myprogram,-c,alpha beta,-h,gamma}
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).
min
args
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
Modula-2
MODULE try;
FROM Arguments IMPORT GetArgs, ArgTable, GetEnv;
FROM InOut IMPORT WriteCard, WriteLn, WriteString;
VAR count, item : SHORTCARD;
storage : ArgTable;
BEGIN
GetArgs (count, storage);
WriteString ('Count ='); WriteCard (count, 4); WriteLn;
item := 0;
REPEAT
WriteCard (item, 4);
WriteString (' : ');
WriteString (storage^ [item]^);
WriteLn;
INC (item)
UNTIL item = count
END try.
Example:
jan@Beryllium:~/modula/test$ try jantje zag eens pruimen hangen
Count = 6
0 : try
1 : jantje
2 : zag
3 : eens
4 : pruimen
5 : hangen
Modula-3
Command line parameters are accessed using the Params module.
MODULE Args EXPORTS Main;
IMPORT IO, Params;
BEGIN
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;
END;
END Args.
Output:
martin@thinkpad:~$ ./prog ./prog martin@thinkpad:~$ ./prog 10 ./prog 10 martin@thinkpad:~$ ./prog 10 20 ./prog 10 20
Nanoquery
//
// command-line arguments
//
// output all arguments
for i in range(0, len(args) - 1)
println args[i]
end
- Output:
$ java -jar ../nanoquery-2.3_1700.jar -b cmdline.nq "alpha beta" -h "gamma" -b cmdline.nq alpha beta -h gamma
Neko
/* command line arguments, neko */
var argc = $asize($loader.args)
/* Display count and arguments, indexed from 0, no script name included */
$print("There are ", argc, " arguments\n")
var arg = 0
while arg < argc $print($loader.args[arg ++= 1], "\n")
- Output:
prompt$ nekoc command-line-arguments.neko prompt$ neko ./command-line-arguments.n -c "alpha beta" -h "gamma" There are 4 arguments -c alpha beta -h gamma
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
Write("\n");
def cl_args = Environment.GetCommandLineArgs(); // also gets program name
foreach (cl_arg in cl_args) Write($"$cl_arg ");
}
}
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
Output:
program arguments: -c "alpha beta" -h "gamma"
Nim
import os
echo "program name: ", getAppFilename()
echo "Arguments:"
for arg in commandLineParams():
echo arg
Nu
In Nu, the special main
function can be declared, which gets passed the cli arguments.
def main [...argv] {
$argv | print
}
- Output:
~> nu cli.nu A B C "Hello World!" ╭───┬──────────────╮ │ 0 │ A │ │ 1 │ B │ │ 2 │ C │ │ 3 │ Hello World! │ ╰───┴──────────────╯
Oberon-2
MODULE CommandLineArguments;
IMPORT
NPCT:Args,
Out := NPCT:Console;
BEGIN
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.
- Output:
Args number: 5 0.- : bin/CommandLineArguments 1.- : -c 2.- : alpha beta 3.- : -h 4.-: gamma
Objeck
class Line {
function : Main(args : String[]) ~ Nil {
each(i : args) {
args[i]->PrintLine();
};
}
}
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]);
}
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)
done
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 *)
Arg.parse
speclist
(fun x -> raise (Arg.Bad ("Bad argument : " ^ x)))
usage;
Printf.printf " %b %d '%s'\n" !somebool !someint !somestr
$ ocaml arg.ml --help usage: arg.ml [-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 --help Display this list of options $ ocaml arg.ml -d 4 -b -s blabla true 4 'blabla' $ ocaml arg.ml false 0 ''
Odin
package main
import "core:os"
import "core:fmt"
main :: proc() {
fmt.println(os.args)
}
// Run: ./program -c "alpha beta" -h "gamma"
// Output: ["./program", "-c", "alpha beta", "-h", "gamma"]
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
Oz
Raw arguments
Like in C, but without the program name:
functor
import Application System
define
ArgList = {Application.getArgs plain}
{ForAll ArgList System.showInfo}
{Application.exit 0}
end
Preprocessed arguments
functor
import Application System
define
ArgSpec =
record(
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}
end
Pascal
Free Pascal
Program listArguments(input, output, stdErr);
Var
i: integer;
Begin
writeLn('program was called from: ',paramStr(0));
For i := 1 To paramCount() Do
Begin
writeLn('argument',i:2,' : ', paramStr(i));
End;
End.
- Output:
./Commandlinearguments -c "alpha beta" -h "gamma" program was called from: /home/user/Documents/GitHub/rosettacode/Commandlinearguments argument 1 : -c argument 2 : alpha beta argument 3 : -h argument 4 : gamma
Perl
@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,
);
Phix
with javascript_semantics constant cmd = command_line() ?cmd if cmd[1]=cmd[2] then printf(1,"Compiled executable name: %s\n",{cmd[1]}) else 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.
- Output:
desktop/Phix (Windows, Linux would be fairly similar but obviously with different paths):
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>
pwa/p2js: There isn't really a command line, you always get a result of length 2.
{"p2js","file:///C:/Program%20Files%20(x86)/Phix/pwa/test.htm"} Interpreted (using p2js) source name: file:///C:/Program%20Files%20(x86)/Phix/pwa/test.htm
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.
<?php
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
Picat
Picat has no built-in option parser, and the user must write a specific parser for each use case. The arguments to a Picat programs are available via main/1
as a list of strings.
main(ARGS) =>
println(ARGS).
main(_) => true.
- Output:
picat command_line_arguments.pi -c "alpha beta" -h "gamma" [-c,alpha beta,-h,gamma]
See the task Command-line_arguments for a simple option parser.
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)
(bye)
Output:
$ ./myprogram -c "alpha beta" -h "gamma" Got 'c': alpha beta Got 'h': gamma
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;
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');
endfor;
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
? COMMAND$
? COMMAND$(0)
DO WHILE(LEN(COMMAND$(i)))
PRINT "The argument "; i; " is "; COMMAND$(i)
i = i + 1
LOOP
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
}
Prolog
The command line arguments supplied to a Prolog interpreter can be accessed by passing os_argv
to current_prolog_flag/2
.
:-
current_prolog_flag(os_argv, Args),
write(Args).
Alternatively, argv
can be used to access only the arguments *not* consumed by the Prolog interpreter.
:-
current_prolog_flag(argv, Args),
write(Args).
This omits the interpreter name, the input Prolog filename, and any other arguments directed at the Prolog interpreter.
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;
PureBasic
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
PrintN(ProgramParameter())
n-1
Wend
Print(#CRLF$+"Press Enter")
Input()
CloseConsole()
EndIf
Reading specific parameters
You can specify which parameter 'n' to read.
If OpenConsole()
Define n
PrintN("Reading specific pameters")
For n=0 To CountProgramParameters()
PrintN(ProgramParameter(n))
Next
Print(#CRLF$+"Press Enter")
Input()
CloseConsole()
EndIf
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.
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)) {
eval(parse(text=args[[i]]))
}
}
print(a*2)
print(b*3)
(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!
Racket
The following is the simplest program that prints the command-line arguments:
#lang racket
(current-command-line-arguments)
You can also explicitly print each argument to standard output:
#lang racket
(for ([arg (current-command-line-arguments)]) (displayln arg))
Raku
(formerly 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; for more detailed information see: https://docs.raku.org/language/create-cli
# with arguments supplied
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5
8
# missing argument:
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3
Usage:
-e '...' x y
If the program is stored in a file, the file name is printed instead of -e '...'
.
RapidQ
PRINT "This program is named "; Command$(0)
FOR i=1 TO CommandCount
PRINT "The argument "; i; " is "; Command$(i)
NEXT i
Raven
ARGS print
stack (6 items)
0 => "raven"
1 => "myprogram"
2 => "-c"
3 => "alpha beta"
4 => "-h"
5 => "gamma"
REALbasic
Function Run(args() as String) As Integer
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function
Output (given arguments: --foo !bar "bat bang"):
appName.exe --foo !bar bat bang
REXX
The entire command line arguments (as a single string) are passed by REXX to the program.
say 'command arguments:'
say arg(1)
Input:
myprogram -c "alpha beta" -b "gamma"
However, in the above example (as shown), it's suggested 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)
x=word(aaa,j)
if left(x,1)=='-' then opts=opts x /*Option? Then add to opts.*/
else data=data x /*Must be data. Add to data.*/
end
/*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
say 'options='opts
say ' data='data
- Note to users of Microsoft Windows and Regina REXX
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 (along to the program being invoked) 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"
- 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.
- 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.
- Workaround
A workaround would be to create a wrapper around the rexx interpreter that encodes the command-line before calling rexx. The rexx application then decodes it. Some rexx interpreters, such as regina also provide a !-a switch as a workaround.
Ring
see copy("=",30) + nl
see "Command Line Parameters" + nl
see "Size : " + len(sysargv) + nl
see sysargv
see copy("=",30) + nl
for x = 1 to len(sysargv)
see x + nl
next
Ruby
Command line arguments are available in the constant Object::ARGV.
myprog:
#! /usr/bin/env ruby
p ARGV
myprog a -h b c => ["a","-h","b","c"]
Rust
use std::env;
fn main(){
let args: Vec<_> = env::args().collect();
println!("{:?}", args);
}
Run:
./program -c "alpha beta" -h "gamma"
["./program", "-c", "alpha beta", "-h", "gamma"]
S-lang
The command-line arguments exist in the array __argv:
variable a;
foreach a (__argv)
print(a);
Note 1: This array can be changed by calling
__set_argc_argv(new_argv);
Note 2: When a script is run as a parameter to slsh, __argv does not include slsh. __argv[0] is simply the name of the script.
The same is true if running a script via the editor jed, as in:
jed -script FILE [arg ...]
However, when [x/w]jed is entered normally, __argv consists of the command-line for the editor itself, with __argv[0] == jed or /path/to/jed or the equivalent.
Sather
class MAIN is
main(args:ARRAY{STR}) is
loop
#OUT + args.elt! + "\n";
end;
end;
end;
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
prints
/home/home/rosetta/sather/a.out arg1 arg2 arg3
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("", ", ", ".")}")
Scheme
(define (main args)
(for-each (lambda (arg) (display arg) (newline)) args))
Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: i is 0;
begin
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;
Sidef
Command line arguments are available in the ARGV array.
say ARGV;
- Output:
% myprog -c "alpha beta" -h "gamma" ['-c', 'alpha beta', '-h', 'gamma']
Slate
StartupArguments do: [| :arg | inform: arg]
Slope
Command line arguments are available in the sys-args list.
(display sys-args)
Smalltalk
(1 to: Smalltalk getArgc) do: [ :i |
(Smalltalk getArgv: i) displayNl
]
Smalltalk commandLineArguments printCR.
Smalltalk commandLineArguments do:[:each | each printCR]
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "printargs" )
@( description, "Retrieve the list of command-line arguments given to the program." )
@( description, "Example command line: " )
@( description, "myprogram -c 'alpha beta' -h 'gamma'" )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Command-line_arguments" );
pragma license( unrestricted );
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
procedure printargs is
begin
put_line( "The command is '" & command_line.command_name & "'" );
for Arg in 1..command_line.argument_count loop
put( "Argument" ) @ (Arg ) @ ( " is '" ) @
( command_line.argument(Arg) ) @ ("'");
new_line;
end loop;
end printargs;
Standard ML
print ("This program is named " ^ CommandLine.name () ^ ".\n");
val args = CommandLine.arguments ();
Array.appi
(fn (i, x) => print ("the argument #" ^ Int.toString (i+1) ^ " is " ^ x ^ "\n"))
(Array.fromList args);
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])")
}
Alternately:
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])!)")
}
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])!)")
}
Tailspin
$ARGS -> !OUT::write
- Output:
[-c, alpha beta, -h, gamma]
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)
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
Transd
#lang transd
MainModule: {
_start: (λ
(textout "Number of arguments: " @numArgs
"\nArgument list: " @progArgs)
)
}
Linux command ('tree3' is the name of Transd interpreter):
tree3 progname -c "alpha beta" -h "gamma"
- Output:
Number of arguments: 5 Argument list: ["progname", "-c", "alpha beta", "-h", "gamma"]
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)
@(collect)
@arg
@(end)
@(output)
My args are: {@(rep)@arg, @(last)@arg@(end)}
@(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>`)))
- Output:
$ 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!
UNIX Shell
Bourne Shell
To retrieve the entire list of arguments:
WHOLELIST="$@"
To retrieve the second and fifth arguments:
SECOND=$2
FIFTH=$5
Ursa
In Ursa, all command line arguments (including the program name as invoked) are contained in the string stream args.
#
# command-line arguments
#
# output all arguments
for (decl int i) (< i (size args)) (inc i)
out args<i> endl console
end for
Sample shell session in the Bourne shell:
$ ursa cmdlineargs.u "alpha beta" -h "gamma" cmdlineargs.u alpha beta -h gamma $
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 < option[ keyword: 'c', parameters: <'alpha','beta'>], option[ position: 1, keyword: 'h', parameters: <'gamma'>], option[ position: 2, longform: true, keyword: 'foo', parameters: <'bar','baz'>]>
V
The arguments to the program are stored in the stack,
args.v
$stack puts
./args.v a b c
=[args.v a b c]
vbScript
'Command line arguments can be accessed all together by
For Each arg In Wscript.Arguments
Wscript.Echo "arg=", arg
Next
'You can access only the named arguments such as /arg:value
For Each arg In Wscript.Arguments.Named
Wscript.Echo "name=", arg, "value=", Wscript.Arguments.Named(arg)
Next
'Or just the unnamed arguments
For Each arg In Wscript.Arguments.Unnamed
Wscript.Echo "arg=", arg
Next
Visual Basic
Like Qbasic, Visual Basic returns all of the args in the built-in variable Command$
:
Sub Main
MsgBox Command$
End Sub
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
Console.WriteLine(token)
Next
End Sub
V (Vlang)
This assumes that the following script, myscript.v, is run as follows: $ v run myscript.v -c "alpha beta" -h "gamma"
import os
fn main() {
for i, x in os.args[1..] {
println("the argument #$i is $x")
}
}
- Output:
the argument #0 is -c the argument #1 is alpha beta the argument #2 is -h the argument #3 is gamma
Wren
This assumes that the following script, Command-line_arguments.wren, is run as follows: $ wren Command-line_arguments.wren -c "alpha beta" -h "gamma"
import "os" for Process
System.print(Process.arguments)
- Output:
[-c, alpha beta, -h, gamma]
XPL0
Characters following the program name are copied into a buffer that is accessible as device 8. This displays the example command line with quote marks stripped off.
int C;
[loop [C:= ChIn(8);
if C = \EOF\$1A then quit;
ChOut(0, C);
];
CrLf(0);
]
- Output:
-c alpha beta -h gamma
zkl
File myprogram.zkl:
System.argv.println();
vm.arglist.println();
zkl myprogram -c "alpha beta" -h "gamma"
- Output:
L("/home/craigd/Projects/ZKL/Bin/zkl","myprogram","-c","alpha beta","-h","gamma") L("-c","alpha beta","-h","gamma")
- Programming Tasks
- Solutions by Programming Task
- Selection/Short Circuit/Console Program Basics
- Basic language learning
- Programming environment operations
- Initialization
- 11l
- 8080 Assembly
- 8086 Assembly
- AArch64 Assembly
- Ada
- Aikido
- Aime
- ALGOL 68
- Amazing Hopper
- AppleScript
- ARM Assembly
- Arturo
- AutoHotkey
- AWK
- Babel
- BASIC
- BaCon
- Batch File
- BBC BASIC
- Blue
- BQN
- Bracmat
- C
- C sharp
- C++
- C3
- Clean
- Clojure
- CLU
- COBOL
- CoffeeScript
- Common Lisp
- Cowgol
- D
- Dart
- DCL
- Delphi
- Déjà Vu
- Draco
- E
- Eiffel
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Euphoria
- F Sharp
- Factor
- Fancy
- Fantom
- Forth
- Fortran
- FreeBASIC
- Frink
- FunL
- Gambas
- Genie
- Global Script
- Go
- Groovy
- Harbour
- Haskell
- HicEst
- Icon
- Unicon
- Icon Programming Library
- Io
- Ioke
- J
- Jakt
- Java
- JavaScript
- Joy
- Jq
- Jsish
- Julia
- Klong
- Kotlin
- Lang
- Lasso
- LFE
- Liberty BASIC
- Lingo
- CommandLine Xtra
- Logo
- LSE64
- Lua
- M2000 Interpreter
- Mathematica
- Wolfram Language
- Mercury
- Min
- MMIX
- Modula-2
- Modula-3
- Nanoquery
- Neko
- Nemerle
- NetRexx
- Nim
- Nu
- Oberon-2
- Objeck
- Objective-C
- OCaml
- Odin
- Oforth
- Oz
- Pascal
- Free Pascal
- Perl
- Phix
- PHP
- Picat
- PicoLisp
- PL/I
- Pop11
- PowerBASIC
- PowerShell
- Prolog
- Pure
- PureBasic
- Python
- R
- Racket
- Raku
- RapidQ
- Raven
- REALbasic
- REXX
- Ring
- Ruby
- Rust
- S-lang
- Sather
- Scala
- Scheme
- Seed7
- Sidef
- Slate
- Slope
- Smalltalk
- SparForte
- Standard ML
- Swift
- Tailspin
- Tcl
- Toka
- Transd
- TXR
- UNIX Shell
- Ursa
- Ursala
- V
- VbScript
- Visual Basic
- Visual Basic .NET
- V (Vlang)
- Wren
- XPL0
- Zkl
- Axe/Omit
- Brainf***/Omit
- Bc/Omit
- Commodore BASIC/Omit
- Dc/Omit
- EasyLang/Omit
- GUISS/Omit
- Lotus 123 Macro Scripting/Omit
- M4/Omit
- Maxima/Omit
- Metafont/Omit
- MUMPS/Omit
- PARI/GP/Omit
- PostScript/Omit
- Retro/Omit
- SmileBASIC/Omit
- TI-89 BASIC/Omit
- Vim Script/Omit
- ZX Spectrum Basic/Omit
- Pages with too many expensive parser function calls