Command-line arguments: Difference between revisions

no edit summary
(add bqn)
No edit summary
 
(37 intermediate revisions by 28 users not shown)
Line 11:
=={{header|11l}}==
<code>:argv</code> is a list containing all command line arguments, including the program name.
<langsyntaxhighlight lang="11l">:start:
print(‘Program name: ’:argv[0])
print("Arguments:\n":argv[1..].join("\n"))</langsyntaxhighlight>
 
=={{header|8080 Assembly}}==
Line 25:
everything CP/M gives it.
 
<langsyntaxhighlight 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
Line 70:
cmdln: db 'Command line: $'
file1: db 13,10,'File 1: $'
file2: db 13,10,'File 2: $'</langsyntaxhighlight>
 
{{out}}
Line 93:
 
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}}==
In Ada95 and later versions, command line arguments are available through the predefined package Ada.Command_Line. In Ada83, this would be implementation dependent.
 
<langsyntaxhighlight lang="ada">with Ada.Command_line; use Ada.Command_Line;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 111 ⟶ 171:
end loop;
New_Line;
end Print_Commands;</langsyntaxhighlight>
 
=== Alternative version using Matreshka ===
Line 117 ⟶ 177:
Uses [http://forge.ada-ru.org/matreshka Matreshka]
 
<langsyntaxhighlight lang="ada">with Ada.Wide_Wide_Text_IO;
 
with League.Application;
Line 128 ⟶ 188:
(League.Application.Arguments.Element (J).To_Wide_Wide_String);
end loop;
end Main;</langsyntaxhighlight>
 
=={{header|Aikido}}==
The arguments are passed to the program as a vector of strings called <em>args</em>
<langsyntaxhighlight lang="aikido">
 
foreach arg in args {
Line 138 ⟶ 198:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer i;
 
i = 0;
Line 148 ⟶ 208:
o_byte('\n');
i += 1;
}</langsyntaxhighlight>
 
=={{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}}
<langsyntaxhighlight lang="algol68">main:(
FOR i TO argc DO
printf(($"the argument #"g(-0)" is "gl$, i, argv(i)))
OD
)</langsyntaxhighlight>
Linux command:
/usr/bin/a68g Command-line_arguments.a68 - 1 2 3 ...
Line 172 ⟶ 232:
<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">
<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>
</lang>
VERSION 1:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
 
Line 188 ⟶ 248:
next
exit(0)
</syntaxhighlight>
</lang>
VERSION 2:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
 
Line 201 ⟶ 261:
++i,{argc,i}jle(__CNT_ARGS__)
exit(0)
</syntaxhighlight>
</lang>
VERSION 3:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <hopper.h>
 
Line 216 ⟶ 276:
}
exit(0)
</syntaxhighlight>
</lang>
VERSION 4:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <natural.h>
#include <hopper.h>
Line 231 ⟶ 291:
remember ( argument 'i' ); put a new line and print it; finally increment 'i' ).
exit(0)
</syntaxhighlight>
</lang>
ETCETERA...
{{out}}
Line 244 ⟶ 304:
=={{header|AppleScript}}==
 
<langsyntaxhighlight lang="applescript">
#!/usr/bin/env osascript
-- Print first argument
Line 250 ⟶ 310:
return (item 1 of argv)
end run
</syntaxhighlight>
</lang>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program commandLine.s */
Line 317 ⟶ 377:
bx lr @ return
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">loop arg 'a [
print a
]</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
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). "
<langsyntaxhighlight lang="autohotkey">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\""</langsyntaxhighlight>
 
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 343 ⟶ 403:
print "Argument " l " is " ARGV[l]
}
}</langsyntaxhighlight>
 
=={{header|Babel}}==
Invoke Babel in interactive mode with arguments using the -i switch:
 
<syntaxhighlight lang ="babel">babel -i Larry Mo Curly</langsyntaxhighlight>
 
Print the argv list with newlines:
 
<syntaxhighlight lang ="babel">argv prn !</langsyntaxhighlight>
 
{{out}}
Line 362 ⟶ 422:
Print the argv list with spaces:
 
<syntaxhighlight lang ="babel">argv prs !</langsyntaxhighlight>
 
{{out}}
Line 369 ⟶ 429:
To access an individual argument, use the ith operator to select an element from the argv list; print with newline using say:
 
<syntaxhighlight lang ="babel">argv 1 ith say !</langsyntaxhighlight>
 
{{out}}
Line 380 ⟶ 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.)
 
<langsyntaxhighlight lang="qbasic">PRINT "args: '"; COMMAND$; "'"</langsyntaxhighlight>
 
Sample output:
Line 389 ⟶ 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>).
 
<langsyntaxhighlight lang="freebasic">DIM i AS INTEGER
 
PRINT COMMAND$
Line 402 ⟶ 462:
FOR i = 0 TO __FB_ARGC__ - 1
PRINT "arg "; i; " = '"; *__FB_ARGV__[i]; "'"
NEXT i</langsyntaxhighlight>
 
Sample output:
Line 417 ⟶ 477:
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="freebasic">' Command line arguments including program name
PRINT "Entire command line: ", ARGUMENT$
 
Line 425 ⟶ 485:
PRINT " " & cli$[i];
NEXT
PRINT</langsyntaxhighlight>
 
{{out}}
Line 440 ⟶ 500:
=={{header|Batch File}}==
{{works with|Windows NT|4 or later (includes Windows XP and onward)}}
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
 
Line 454 ⟶ 514:
for /l %%a in (1,1,%count%) do (
echo !parameter[%%a]!
)</langsyntaxhighlight>
 
Another way of doing it
 
<langsyntaxhighlight lang="dos">::args2.cmd
@echo off
setlocal enabledelayedexpansion
Line 480 ⟶ 540:
for /l %%i in (1,1,%p#%) do (
echo p%%i=!p%%i!
)</langsyntaxhighlight>
 
Invocation:
 
<langsyntaxhighlight lang="dos">>args2 foo "bar baz" quux
fn=d:\bin\args2.cmd
p0=args2
Line 492 ⟶ 552:
p2=bar baz
p3=quux
</syntaxhighlight>
</lang>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang ="bbcbasic">PRINT @cmd$</langsyntaxhighlight>
 
=={{languageheader|BQNBlue}}==
 
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</langsyntaxhighlight>
 
should show the full list of args.
Line 507 ⟶ 604:
=={{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.
<syntaxhighlight lang="text">whl'(arg$:?a&out$(str$("next arg=" !a)))</langsyntaxhighlight>
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>
Line 539 ⟶ 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.
 
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
 
Line 549 ⟶ 646:
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="csharp">using System;
 
namespace RosettaCode {
Line 562 ⟶ 659:
}
}
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="csharp">using System;
 
namespace RosettaCode {
Line 575 ⟶ 672:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Command line arguments are passed the same way as in C.
 
This example uses <code><iostream></code>. Traditional C-style Ii/Oo also works.
 
<langsyntaxhighlight 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)
{
stdio::cout << printfn("This program is named %s.", << argvargs[0] << std::endl);
for (int i = 1; i < args.len; i++)
std::cout << "There are " << argc-1 << " arguments given." << std::endl;
{
for (int i = 1; i < argc; ++i)
stdio::cout << printfn("the argument #" << i << "%d is %s\n", <<i, argvargs[i] << std::endl);
}
}</syntaxhighlight>
 
return 0;
}</lang>
 
=={{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).
 
<langsyntaxhighlight lang="clean">import ArgEnv
 
Start = getCommandLine</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 605 ⟶ 715:
The value of ''*command-line-args*'' is a sequence of the supplied command line arguments, or ''nil'' if none were supplied.
 
<langsyntaxhighlight Clojurelang="clojure">(dorun (map println *command-line-args*))</langsyntaxhighlight>
 
=={{header|CLU}}==
Line 615 ⟶ 725:
Note that unlike C, the program name itself is not included in the list of arguments.
 
<langsyntaxhighlight lang="clu">% This program needs to be merged with PCLU's "useful.lib",
% where get_argv lives.
%
Line 628 ⟶ 738:
stream$putl(po, "arg: " || arg)
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>$ ./cmdline -c "alpha beta" -h "gamma"
Line 643 ⟶ 753:
 
Getting the arguments in one go, exactly as they were passed in:
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. accept-all-args.
Line 656 ⟶ 766:
GOBACK
.</langsyntaxhighlight>
 
Getting the arguments one at a time, with arguments being split by whitespace if not in quotes:
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. accept-args-one-at-a-time.
Line 675 ⟶ 785:
GOBACK
.</langsyntaxhighlight>
 
Passing arguments from UNIX/Linux Systems to COBOL.
{{works with|OpenCOBOL}}
{{works with|gnuCOBOL}}
<langsyntaxhighlight lang="cobol">
*>Created By Zwiegnet 8/19/2004
 
Line 737 ⟶ 847:
STOP RUN.
 
.</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
{{works with|Node.js}}
<langsyntaxhighlight lang="coffeescript">
console.log arg for arg in process.argv
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 751 ⟶ 861:
The following function could be used to create a uniform way to access the arguments:
 
<langsyntaxhighlight lang="lisp">(defun argv ()
(or
#+clisp (ext:argv)
Line 762 ⟶ 872:
#+allegro (sys:command-line-arguments)
#+lispworks sys:*line-arguments-list*
nil))</langsyntaxhighlight>
 
=={{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}}==
<langsyntaxhighlight lang="d">void main(in string[] args) {
import std.stdio;
 
foreach (immutable i, arg; args[1 .. $])
writefln("#%2d : %s", i + 1, arg);
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="csharp">main(List<String> args) {
for(var arg in args)
print(arg);
}</langsyntaxhighlight>
 
=={{header|DCL}}==
case is not preserved unless the parameter is in quotes
<langsyntaxhighlight DCLlang="dcl">$ i = 1
$ loop:
$ write sys$output "the value of P''i' is ", p'i
$ i = i + 1
$ if i .le. 8 then $ goto loop</langsyntaxhighlight>
{{out}}
<pre>$ @command_line_arguments -c "alpha beta" -h "gamma"
Line 798 ⟶ 944:
=={{header|Delphi}}==
 
<langsyntaxhighlight 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"
 
Line 811 ⟶ 957:
// param[3] = -h
// param[4] = gamma
</syntaxhighlight>
</lang>
 
=={{header|Déjà Vu}}==
Command line arguments are found in <code>!args</code> and <code>!opts</code>.
 
<langsyntaxhighlight lang="dejavu">for i range 0 -- len !args:
print\( "Argument #" i " is " )
. get-from !args i
Line 824 ⟶ 970:
 
if has !opts :four:
!. get-from !opts :four</langsyntaxhighlight>
{{out}}
<pre>$ vu args-3.deja one two -c three --four=five
Line 835 ⟶ 981:
 
The order of command line ''options'' is lost.
 
=={{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.
This is however a limitation of the CP/M operating system, and not of Draco.
 
<syntaxhighlight lang="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</syntaxhighlight>
 
{{out}}
 
<pre>A>param -c "alpha beta" -h "gamma"
1: '-C'
2: '"ALPHA'
3: 'BETA"'
4: '-H'
5: '"GAMMA"'</pre>
 
=={{header|E}}==
 
<syntaxhighlight lang ="e">interp.getArgs()</langsyntaxhighlight>
 
=={{header|Eiffel}}==
Line 844 ⟶ 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.
 
<langsyntaxhighlight lang="eiffel ">class
APPLICATION
inherit
Line 860 ⟶ 1,035:
io.read_line -- Keep console window open
end
end</langsyntaxhighlight>
 
Output (for command line arguments: -c "alpha beta" -h "gamma"):
Line 869 ⟶ 1,044:
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
public program()
{
program_arguments.forEvery::(int i)
{ console.printLine("Argument ",i," is ",program_arguments[i]) }
}</langsyntaxhighlight>
{{out}}
<pre>
Line 889 ⟶ 1,064:
=={{header|Elixir}}==
Elixir provides command line arguments via the <tt>System.argv()</tt> function.
<langsyntaxhighlight lang="elixir">#!/usr/bin/env elixir
IO.puts 'Arguments:'
Enum.map(System.argv(),&IO.puts(&1))</langsyntaxhighlight>
Example run:
<langsyntaxhighlight lang="bash">$ ./show-args.exs a b=2 --3 -4
Arguments:
a
b=2
--3
-4</langsyntaxhighlight>
 
=={{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}}==
When used as a script language the arguments is a list to the main/1 function. When compiled use init:get_arguments/0
<syntaxhighlight lang ="erlang">3> init:get_arguments().</langsyntaxhighlight>
result
<langsyntaxhighlight lang="erlang">[{root,["/usr/erlang/erl5.5"]},
{progname,["erl"]},
{home,["/home/me"]},
{c,["alpha beta"]},
{h,["gamma"]}]</langsyntaxhighlight>
 
init:get_argument(name) can be used to fetch value of a particular flag
 
<langsyntaxhighlight lang="erlang">4> init:get_argument(h).
{ok,[["gamma"]]}
5> init:get_argument(c).
{ok,[["alpha beta"]]}</langsyntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">constant cmd = command_line()
printf(1,"Interpreter/executable name: %s\n",{cmd[1]})
printf(1,"Program file name: %s\n",{cmd[2]})
Line 932 ⟶ 1,110:
printf(1,"#%d : %s\n",{i,cmd[i]})
end for
end if</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="fsharp">#light
[<EntryPoint>]
let main args =
Array.iter (fun x -> printfn "%s" x) args
0</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 947 ⟶ 1,125:
 
=={{header|Fancy}}==
<langsyntaxhighlight lang="fancy">ARGV each: |a| {
a println # print each given command line argument
}</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 961 ⟶ 1,139:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
Line 967 ⟶ 1,145:
 
{{works with|gforth|0.6.2}}
<langsyntaxhighlight lang="forth">\ args.f: print each command line argument on a separate line
: main
argc @ 0 do i arg type cr loop ;
 
main bye</langsyntaxhighlight>
 
Here is output from a sample run.
<langsyntaxhighlight lang="forth">$ gforth args.f alpha "beta gamma" delta
gforth
args.f
Line 980 ⟶ 1,158:
beta gamma
delta
$</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|2003 and later}}
<langsyntaxhighlight lang="fortran">program command_line_arguments
 
implicit none
Line 1,000 ⟶ 1,178:
 
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.
 
Sample usage:
<syntaxhighlight lang="text">> ./a.out -c "alpha beta" -h "gamma"
./a.out
-c
alpha beta
-h
gamma</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Program (myprogram.exe) invoke as follows:
Line 1,020 ⟶ 1,198:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,029 ⟶ 1,207:
=={{header|Frink}}==
Arguments to a program are available in the <CODE>ARGS</CODE> array variable.
<langsyntaxhighlight lang="frink">
println[ARGS]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<syntaxhighlight lang ="funl">println( args )</langsyntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=a1374aa441520314ad0c7decb1e91c97 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">PUBLIC SUB main()
DIM l AS Integer
DIM numparms AS Integer
Line 1,047 ⟶ 1,225:
PRINT l; " : "; parm
NEXT
END</langsyntaxhighlight>
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/*
Command line arguments, in Genie
Line 1,069 ⟶ 1,247:
// to reiterate, args[0] is the command
if args[0] is not null
print "\nWith Genie, args[0] is the command: %s", args[0]</langsyntaxhighlight>
 
{{out}}
Line 1,088 ⟶ 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.
<langsyntaxhighlight Globallang="global Scriptscript">λ 'as. impmapM (λ 'a. print qq{Argument: §(a)\n}) as</langsyntaxhighlight>
 
=={{header|Go}}==
<syntaxhighlight lang="go">
<lang go>
package main
import (
Line 1,103 ⟶ 1,281:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
Command-line arguments are accessible via the '''args''' list variable. The following is saved as the file "Echo.groovy":
<syntaxhighlight lang ="groovy">println args</langsyntaxhighlight>
 
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 1,120 ⟶ 1,298:
=={{header|Harbour}}==
Uses the Harbour-specific hb_PValue() function
<langsyntaxhighlight lang="visualfoxpro">PROCEDURE Main()
 
LOCAL i
Line 1,128 ⟶ 1,306:
NEXT
 
RETURN</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,135 ⟶ 1,313:
 
myprog.hs:
<langsyntaxhighlight lang="haskell">import System
main = getArgs >>= print</langsyntaxhighlight>
<pre>
myprog a -h b c
Line 1,143 ⟶ 1,321:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="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</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Command line parameters are passed to Icon/Unicon programs as a list of strings.
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
every write(!arglist)
end</langsyntaxhighlight>
 
{{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}}==
<langsyntaxhighlight lang="io">System args foreach(a, a println)</langsyntaxhighlight>
 
=={{header|Ioke}}==
<syntaxhighlight lang ="ioke">System programArguments each(println)</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,166 ⟶ 1,344:
The global <code>ARGV</code> holds the command line arguments. Thus, a program to display them:
 
<syntaxhighlight lang J="j"> ARGV</langsyntaxhighlight>
 
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) {
System.out.println("There are " + args.length + " arguments given.");
Line 1,176 ⟶ 1,382:
System.out.println("The argument #" + (i+1) + " is " + args[i] + " and is at index " + i);
}
}</langsyntaxhighlight>
 
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 1,182 ⟶ 1,388:
=={{header|JavaScript}}==
{{works with|Node.js}}
<langsyntaxhighlight lang="javascript">process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});</langsyntaxhighlight>
{{works with|JScript}}
<langsyntaxhighlight lang="javascript">var objArgs = WScript.Arguments;
for (var i = 0; i < objArgs.length; i++)
WScript.Echo(objArgs.Item(i));</langsyntaxhighlight>
{{works with|JScript.NET (compiled with jsc.exe)}}
<langsyntaxhighlight lang="javascript">import System;
var argv:String[] = Environment.GetCommandLineArgs();
for (var i in argv)
print(argv[i]);</langsyntaxhighlight>
{{works with|Rhino}}
{{works with|SpiderMonkey}}
<langsyntaxhighlight lang="javascript">for (var i = 0; i < arguments.length; i++)
print(arguments[i]);</langsyntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">#!/usr/bin/joy
 
argv rest put.</syntaxhighlight>
{{out}}
<pre>["-c" "alpha beta" "-h" "gamma"]</pre>
 
=={{header|jq}}==
Line 1,216 ⟶ 1,429:
$ jq -n '$ARGS' --args a b
 
yields:<langsyntaxhighlight lang="json">{
"positional": [
"a",
Line 1,222 ⟶ 1,435:
],
"named": {}
}</langsyntaxhighlight>
 
Arguments specified with ''--args'' are always read as JSON strings; arguments specified with ''--jsonargs''
Line 1,241 ⟶ 1,454:
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">#!/usr/local/bin/jsish
puts(Info.argv0());
puts(console.args);</langsyntaxhighlight>
 
{{out}}
Line 1,252 ⟶ 1,465:
=={{header|Julia}}==
Works when the Julia program is run as a file argument to julia.exe.
<langsyntaxhighlight Julialang="julia">using Printf
 
prog = Base.basename(Base.source_path())
Line 1,260 ⟶ 1,473:
println(" ", s)
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,277 ⟶ 1,490:
per line:
 
<syntaxhighlight lang="k">
<lang K>
.p'.a
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">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") }
}</langsyntaxhighlight>
{{out}}
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}}==
<langsyntaxhighlight lang="lasso">#!/usr/bin/lasso9
 
iterate($argv) => {
stdoutnl("Argument " + loop_count + ": " + loop_value)
}</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="shell">$ 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</langsyntaxhighlight>
 
=={{header|LFE}}==
 
To demonstrate this, we can start the LFE REPL up with the parameters for this example:
<langsyntaxhighlight lang="shell">
$ ./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:
<langsyntaxhighlight lang="lisp">
> (: init get_arguments)
(#(root ("/opt/erlang/r15b03"))
Line 1,321 ⟶ 1,555:
#(c ("alpha beta"))
#(h ("gamma")))
</syntaxhighlight>
</lang>
 
We can also get specific arguments if we know their keys:
<langsyntaxhighlight lang="lisp">
> (: init get_argument 'c)
#(ok (("alpha beta")))
> (: init get_argument 'h)
#(ok (("gamma")))
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang ="lb">print CommandLine$</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">put the commandline
-- "-c alpha beta -h gamma"</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight lang="lingo">put getCommandLineArgs()
-- ["-c", "alpha beta", "-h", "gamma"]</langsyntaxhighlight>
 
=={{header|Logo}}==
Line 1,349 ⟶ 1,583:
logo file.logo - arg1 arg2 arg3
Then the arguments after the "-" are found in a list in variable :COMMAND.LINE
<langsyntaxhighlight lang="logo">show :COMMAND.LINE
[arg1 arg2 arg3]</langsyntaxhighlight>
Alternatively, make the first line of an executable logo script:
#! /usr/bin/logo -
Line 1,357 ⟶ 1,591:
 
=={{header|LSE64}}==
<langsyntaxhighlight lang="lse64">argc , nl # number of arguments (including command itself)
0 # argument
dup arg dup 0 = || ,t 1 + repeat
drop</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 1,366 ⟶ 1,600:
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:
 
<langsyntaxhighlight lang="lua">print( "Program name:", arg[0] )
 
print "Arguments:"
for i = 1, #arg do
print( i," ", arg[i] )
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,380 ⟶ 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).
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Document a$ = {
Line 1,407 ⟶ 1,641:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
myprogram:
<langsyntaxhighlight Mathematicalang="mathematica">#!/usr/local/bin/MathematicaScript -script
$CommandLine</langsyntaxhighlight>
Output:
<pre>{myprogram,-c,alpha beta,-h,gamma}</pre>
 
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module cmd_line_args.
:- interface.
Line 1,437 ⟶ 1,671:
print_arg(Arg, ArgNum, ArgNum + 1, !IO) :-
io.format("the argument #%d is %s\n", [i(ArgNum), s(Arg)], !IO).
</syntaxhighlight>
</lang>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang ="min">args</langsyntaxhighlight>
 
=={{header|MMIX}}==
<langsyntaxhighlight lang="mmix">argv IS $1
argc IS $0
i IS $2
Line 1,466 ⟶ 1,700:
TRAP 0,Halt,0
 
NewLine BYTE #a,0</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE try;
 
FROM Arguments IMPORT GetArgs, ArgTable, GetEnv;
Line 1,488 ⟶ 1,722:
INC (item)
UNTIL item = count
END try.</langsyntaxhighlight>
Example:
<syntaxhighlight lang="modula-2">
<lang Modula-2>
jan@Beryllium:~/modula/test$ try jantje zag eens pruimen hangen
Count = 6
Line 1,499 ⟶ 1,733:
4 : pruimen
5 : hangen
</syntaxhighlight>
</lang>
 
=={{header|Modula-3}}==
Command line parameters are accessed using the <tt>Params</tt> module.
<langsyntaxhighlight lang="modula3">MODULE Args EXPORTS Main;
 
IMPORT IO, Params;
Line 1,514 ⟶ 1,748:
END;
END;
END Args.</langsyntaxhighlight>
 
Output:
Line 1,531 ⟶ 1,765:
=={{header|Nanoquery}}==
{{trans|Ursa}}
<syntaxhighlight lang="nanoquery">//
<lang Nanoquery>//
// command-line arguments
//
Line 1,538 ⟶ 1,772:
for i in range(0, len(args) - 1)
println args[i]
end</langsyntaxhighlight>
{{out}}
<pre>$ java -jar ../nanoquery-2.3_1700.jar -b cmdline.nq "alpha beta" -h "gamma"
Line 1,548 ⟶ 1,782:
 
=={{header|Neko}}==
<langsyntaxhighlight lang="actionscript">/* command line arguments, neko */
var argc = $asize($loader.args)
 
Line 1,555 ⟶ 1,789:
 
var arg = 0
while arg < argc $print($loader.args[arg ++= 1], "\n")</langsyntaxhighlight>
 
{{out}}
Line 1,567 ⟶ 1,801:
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 1,580 ⟶ 1,814:
foreach (cl_arg in cl_args) Write($"$cl_arg ");
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
In a stand-alone application NetRexx places the command string passed to it in a variable called <tt>arg</tt>.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
-- sample arguments: -c "alpha beta" -h "gamma"
say "program arguments:" arg
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,594 ⟶ 1,828:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import os
echo "program name: ", getAppFilename()
echo "Arguments:"
for arg in commandLineParams():
echo arg</langsyntaxhighlight>
 
=={{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}}==
{{works with|oo2c}}
<langsyntaxhighlight lang="oberon2">
MODULE CommandLineArguments;
IMPORT
Line 1,616 ⟶ 1,868:
Out.String("4.-: ");Out.String(Args.AsString(4));Out.Ln
END CommandLineArguments.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,628 ⟶ 1,880:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Line {
function : Main(args : String[]) ~ Nil {
Line 1,636 ⟶ 1,888:
}
}
</syntaxhighlight>
</lang>
 
=={{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:
<langsyntaxhighlight lang="objc">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]);
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 1,652 ⟶ 1,904:
The program name is also passed as "argument", so the array length is actually one more than the number of program arguments.
 
<langsyntaxhighlight lang="ocaml">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</langsyntaxhighlight>
 
=== Using the [httphttps://camlocaml.inria.fr/pub/docs/manual-ocamlorg/librefapi/Arg.html Arg] module ===
<syntaxhighlight lang="ocaml">(* default values *)
 
<lang ocaml>(* default values *)
let somebool = ref false
let somestr = ref ""
Line 1,679 ⟶ 1,930:
(fun x -> raise (Arg.Bad ("Bad argument : " ^ x)))
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
// Run: ./program -c "alpha beta" -h "gamma"
false 0 <nowiki>''</nowiki>
// Output: ["./program", "-c", "alpha beta", "-h", "gamma"]
</syntaxhighlight>
 
=={{header|Oforth}}==
Line 1,704 ⟶ 1,969:
The first argument is the program name, so this list is never empty.
 
<syntaxhighlight lang Oforth="oforth">System.Args println</langsyntaxhighlight>
 
=={{header|Oz}}==
===Raw arguments===
Like in C, but without the program name:
<langsyntaxhighlight lang="oz">functor
import Application System
define
Line 1,715 ⟶ 1,980:
{ForAll ArgList System.showInfo}
{Application.exit 0}
end</langsyntaxhighlight>
 
===Preprocessed arguments===
<langsyntaxhighlight lang="oz">functor
import Application System
define
Line 1,734 ⟶ 1,999:
{System.showInfo Args.h}
{Application.exit 0}
end</langsyntaxhighlight>
 
=={{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}}==
Line 1,743 ⟶ 2,031:
@ARGV is the array containing all command line parameters
 
<langsyntaxhighlight lang="perl">my @params = @ARGV;
my $params_size = @ARGV;
my $second = $ARGV[1];
my $fifth = $ARGV[4];</langsyntaxhighlight>
 
If you don't mind importing a module:
 
<langsyntaxhighlight lang="perl">use Getopt::Long;
GetOptions (
'help|h' => \my $help,
'verbose|v' => \my $verbose,
);</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<span style="color: #0000FF;">?</span><span style="color: #000000;">cmd</span>
Line 1,771 ⟶ 2,060:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</langsyntaxhighlight>-->
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.
{{out}}
desktop/Phix (Windows, Linux would be fairly similar but obviously with different paths):
<pre>
C:\Program Files (x86)\Phix>p testcl -c "alpha beta" -h "gamma"
Line 1,801 ⟶ 2,091:
#6 : gamma
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>
 
Line 1,806 ⟶ 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.
 
<langsyntaxhighlight lang="php"><?php
$program_name = $argv[0];
$second_arg = $argv[2];
$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}}==
Line 1,827 ⟶ 2,135:
and then '[http://software-lab.de/doc/refL.html#load load]' all remaining
command line arguments.
<langsyntaxhighlight PicoLisplang="picolisp">#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
 
(de c ()
Line 1,836 ⟶ 2,144:
 
(load T)
(bye)</langsyntaxhighlight>
Output:
<pre>$ ./myprogram -c "alpha beta" -h "gamma"
Line 1,843 ⟶ 2,151:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
/* The entire command line except the command word itself is passed */
/* to the parameter variable in PL/I. */
Line 1,852 ⟶ 2,160:
 
end program;
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 1,858 ⟶ 2,166:
variable poparglist contains list of command line arguments (as strings). One can use iteration over list to process then (for example print).
 
<langsyntaxhighlight lang="pop11">lvars arg;
for arg in poparglist do
printf(arg, '->%s<-\n');
endfor;</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="powerbasic">? "args: '"; COMMAND$; "'"</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="powerbasic">'these two both return ALL args
? COMMAND$
? COMMAND$(0)
Line 1,875 ⟶ 2,183:
PRINT "The argument "; i; " is "; COMMAND$(i)
i = i + 1
LOOP</langsyntaxhighlight>
 
=={{header|PowerShell}}==
In PowerShell the arguments to a script can be accessed with the <code>$args</code> array:
<langsyntaxhighlight lang="powershell">$i = 0
foreach ($s in $args) {
Write-Host Argument (++$i) is $s
}</langsyntaxhighlight>
 
=={{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}}==
Arguments are in global variables, argc and argv.
 
<langsyntaxhighlight lang="pure">
using system;
 
printf "There are %d command line argumants\n" argc;
puts "They are " $$ map (puts) argv;
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
Line 1,898 ⟶ 2,219:
===Reading all parameters===
You can easily read all parameters by using ProgramParameter() without argument.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define n=CountProgramParameters()
PrintN("Reading all parameters")
Line 1,908 ⟶ 2,229:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
===Reading specific parameters===
You can specify which parameter 'n' to read.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define n
PrintN("Reading specific pameters")
Line 1,920 ⟶ 2,241:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{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:
 
<langsyntaxhighlight lang="python">import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)</langsyntaxhighlight>
 
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,940 ⟶ 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
 
<langsyntaxhighlight Rlang="r">R CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out</langsyntaxhighlight>
 
from the commandline, with the following text in <tt>test.r</tt>:
 
<langsyntaxhighlight Rlang="r"># Read the commandline arguments
args <- (commandArgs(TRUE))
 
Line 1,961 ⟶ 2,282:
}
print(a*2)
print(b*3)</langsyntaxhighlight>
 
(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,983 ⟶ 2,304:
The following is the simplest program that prints the command-line arguments:
 
<langsyntaxhighlight lang="scheme">#lang racket
(current-command-line-arguments)</langsyntaxhighlight>
 
You can also explicitly print each argument to standard output:
 
<langsyntaxhighlight lang="scheme">#lang racket
 
(for ([arg (current-command-line-arguments)]) (displayln arg))</langsyntaxhighlight>
 
=={{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; seefor [http://perlcabal.org/syn/S06.html#Declaring_a_MAIN_subroutinemore Synopsisdetailed 6]information orsee: [http https://perlgeekdocs.deraku.org/enlanguage/article/5create-to-6#post_14|5-to-6].cli
 
<syntaxhighlight lang="raku" perl6line># with arguments supplied
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5
8
Line 2,003 ⟶ 2,324:
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3
Usage:
-e '...' x y</langsyntaxhighlight>
 
If the program is stored in a file, the file name is printed instead of <code>-e '...'</code>.
 
=={{header|RapidQ}}==
<langsyntaxhighlight lang="rapidq">PRINT "This program is named "; Command$(0)
FOR i=1 TO CommandCount
PRINT "The argument "; i; " is "; Command$(i)
NEXT i</langsyntaxhighlight>
 
=={{header|Raven}}==
 
<langsyntaxhighlight lang="raven">ARGS print
 
stack (6 items)
Line 2,023 ⟶ 2,344:
3 => "alpha beta"
4 => "-h"
5 => "gamma"</langsyntaxhighlight>
 
=={{header|REALbasic}}==
<langsyntaxhighlight lang="vb">Function Run(args() as String) As Integer
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function</langsyntaxhighlight>
Output (given arguments: ''--foo !bar "bat bang"''):
appName.exe
Line 2,039 ⟶ 2,360:
=={{header|REXX}}==
The entire command line arguments (as a single string) are passed by REXX to the program.
<langsyntaxhighlight lang="rexx">say 'command arguments:'
say arg(1)</langsyntaxhighlight>
Input:
 
Line 2,048 ⟶ 2,369:
only options that start with a minus (-) are to be examined
and assumed to be options.
<langsyntaxhighlight lang="rexx">parse arg aaa /*get the arguments. */
/*another version: */
/* aaa=arg(1) */
Line 2,069 ⟶ 2,390:
say
say 'options='opts
say ' data='data</langsyntaxhighlight>
 
;Note to users of Microsoft Windows and Regina REXX:
Line 2,132 ⟶ 2,453:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
see copy("=",30) + nl
see "Command Line Parameters" + nl
Line 2,141 ⟶ 2,462:
see x + nl
next
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Line 2,147 ⟶ 2,468:
 
myprog:
<langsyntaxhighlight lang="ruby">#! /usr/bin/env ruby
p ARGV</langsyntaxhighlight>
 
myprog a -h b c
Line 2,154 ⟶ 2,475:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::env;
 
fn main(){
let args: Vec<_> = env::args().collect();
println!("{:?}", args);
}</langsyntaxhighlight>
Run:
<syntaxhighlight lang="text">./program -c "alpha beta" -h "gamma"
["./program", "-c", "alpha beta", "-h", "gamma"]</langsyntaxhighlight>
 
=={{header|S-lang}}==
The command-line arguments exist in the array __argv:
<langsyntaxhighlight Slang="s-lang">variable a;
foreach a (__argv)
print(a);
</langsyntaxhighlight>Note 1: This array can be changed by calling
 
__set_argc_argv(new_argv);
Line 2,185 ⟶ 2,506:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main(args:ARRAY{STR}) is
loop
Line 2,191 ⟶ 2,512:
end;
end;
end;</langsyntaxhighlight>
 
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 2,210 ⟶ 2,531:
array of strings, and returns unit. That array contains the command line arguments.
 
<langsyntaxhighlight lang="scala">object CommandLineArguments extends App {
println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}")
}</langsyntaxhighlight>
 
When running a Scala script, where the whole body is executed, the arguments get stored in an array of strings called <code>argv</code>:
 
<langsyntaxhighlight lang="scala">println(s"Received the following arguments: + ${argv.mkString("", ", ", ".")}")</langsyntaxhighlight>
 
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme"> (define (main args)
(for-each (lambda (arg) (display arg) (newline)) args))</langsyntaxhighlight>
 
=={{header|Seed7}}==
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 2,235 ⟶ 2,556:
writeln("The argument #" <& i <& " is " <& argv(PROGRAM)[i]);
end for;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
Command line arguments are available in the ARGV array.
<syntaxhighlight lang ="ruby">say ARGV;</langsyntaxhighlight>
{{out}}
<pre>% myprog -c "alpha beta" -h "gamma"
Line 2,246 ⟶ 2,567:
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">StartupArguments do: [| :arg | inform: arg]</langsyntaxhighlight>
 
=={{header|Slope}}==
Command line arguments are available in the '''sys-args''' list.
<syntaxhighlight lang="slope">(display sys-args)</syntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">(1 to: Smalltalk getArgc) do: [ :i |
(Smalltalk getArgv: i) displayNl
]</langsyntaxhighlight>
 
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">Smalltalk commandLineArguments printCR.
Smalltalk commandLineArguments do:[:each | each printCR]</langsyntaxhighlight>
 
=={{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}}==
 
<langsyntaxhighlight lang="sml">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);</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="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])")
}</langsyntaxhighlight>
 
Alternately:
 
{{works with|Swift|1.2+}}
<langsyntaxhighlight lang="swift">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])!)")
}</langsyntaxhighlight>
{{works with|Swift|1.0-1.1}}
<langsyntaxhighlight lang="swift">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])!)")
}</langsyntaxhighlight>
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
$ARGS -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,303 ⟶ 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:
 
<langsyntaxhighlight lang="tcl">if { $argc > 1 } {
puts [lindex $argv 1]
}</langsyntaxhighlight>
 
(Tcl counts from zero, thus <tt>[lindex $list 1]</tt> retrieves the second item in the list)
Line 2,315 ⟶ 2,665:
number of arguments is provided by #args.
 
<langsyntaxhighlight lang="toka">[ arglist array.get type cr ] is show-arg
[ dup . char: = emit space ] is #=
1 #args [ i #= show-arg ] countedLoop</langsyntaxhighlight>
 
 
=={{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}}==
Line 2,325 ⟶ 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.
 
<langsyntaxhighlight lang="txr">@(next :args)
@(collect)
@arg
Line 2,331 ⟶ 2,700:
@(output)
My args are: {@(rep)@arg, @(last)@arg@(end)}
@(end)</langsyntaxhighlight>
 
<pre>$ ./txr args.txr
Line 2,344 ⟶ 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.
 
<langsyntaxhighlight lang="txrlisp">(tree-case *args*
((a b c) (put-line "got three args, thanks!"))
(else (put-line `usage: @(ldiff *full-args* *args*) <arg1> <arg2> <arg3>`)))</langsyntaxhighlight>
{{out}}
<pre>$ txr command-line-args.txr 1 2
Line 2,358 ⟶ 2,727:
===[[Bourne Shell]]===
To retrieve the entire list of arguments:
<langsyntaxhighlight lang="bash">WHOLELIST="$@"</langsyntaxhighlight>
To retrieve the second and fifth arguments:
<langsyntaxhighlight lang="bash">SECOND=$2
FIFTH=$5</langsyntaxhighlight>
 
=={{header|Ursa}}==
In Ursa, all command line arguments (including the program name as invoked) are contained in the string stream args.
<langsyntaxhighlight lang="ursa">#
# command-line arguments
#
Line 2,372 ⟶ 2,741:
for (decl int i) (< i (size args)) (inc i)
out args<i> endl console
end for</langsyntaxhighlight>
 
Sample shell session in the Bourne shell:
Line 2,387 ⟶ 2,756:
This example application does nothing but display the data
structure on standard output.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
#executable ('parameterized','')
 
clarg = <.file$[contents: --<''>+ _option%LP]>+ ~command.options</langsyntaxhighlight>
Here is a bash terminal session.
<pre>$ clarg -c alpha,beta -h gamma --foo=bar,baz
Line 2,412 ⟶ 2,781:
 
args.v
<langsyntaxhighlight lang="v">$stack puts
 
./args.v a b c
=[args.v a b c]</langsyntaxhighlight>
 
=={{header|vbScript}}==
 
<langsyntaxhighlight lang="vbscript">
'Command line arguments can be accessed all together by
 
Line 2,437 ⟶ 2,806:
Wscript.Echo "arg=", arg
Next
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic}}==
 
Like [[#BASIC|Qbasic]], Visual Basic returns all of the args in the built-in variable <code>Command$</code>:
<langsyntaxhighlight lang="vb">Sub Main
MsgBox Command$
End Sub</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 2,450 ⟶ 2,819:
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.
 
<langsyntaxhighlight lang="vbnet">Sub Main(ByVal args As String())
For Each token In args
Console.WriteLine(token)
Next
End Sub</langsyntaxhighlight>
 
=={{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, myscriptCommand-line_arguments.wren, is run as follows:
$ wren myscriptCommand-line_arguments.wren -c "alpha beta" -h "gamma"
<langsyntaxhighlight ecmascriptlang="wren">import "os" for Process
 
System.print(Process.arguments)</langsyntaxhighlight>
 
{{out}}
Line 2,471 ⟶ 2,859:
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.
<langsyntaxhighlight XPL0lang="xpl0">int C;
[loop [C:= ChIn(8);
if C = \EOF\$1A then quit;
Line 2,477 ⟶ 2,865:
];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 2,486 ⟶ 2,874:
=={{header|zkl}}==
File myprogram.zkl:
<langsyntaxhighlight lang="zkl">System.argv.println();
vm.arglist.println();</langsyntaxhighlight>
zkl myprogram -c "alpha beta" -h "gamma"
{{out}}
Line 2,500 ⟶ 2,888:
{{omit from|Commodore BASIC}}
{{omit from|dc}}
{{omit from|EasyLang|Programs cannot be executed outside the IDE, not even in a command line.}}
{{omit from|GUISS}}
{{omit from|Lotus 123 Macro Scripting}}
43

edits