Command-line arguments: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|J}}) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 11:
=={{header|11l}}==
<code>:argv</code> is a list containing all command line arguments, including the program name.
<
print(‘Program name: ’:argv[0])
print("Arguments:\n":argv[1..].join("\n"))</
=={{header|8080 Assembly}}==
Line 25:
everything CP/M gives it.
<
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: $'</
{{out}}
Line 98:
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.Text_IO; use Ada.Text_IO;
Line 111:
end loop;
New_Line;
end Print_Commands;</
=== Alternative version using Matreshka ===
Line 117:
Uses [http://forge.ada-ru.org/matreshka Matreshka]
<
with League.Application;
Line 128:
(League.Application.Arguments.Element (J).To_Wide_Wide_String);
end loop;
end Main;</
=={{header|Aikido}}==
The arguments are passed to the program as a vector of strings called <em>args</em>
<
foreach arg in args {
Line 138:
}
</syntaxhighlight>
=={{header|Aime}}==
<
i = 0;
Line 148:
o_byte('\n');
i += 1;
}</
=={{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}}
<
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 ...
Line 172:
<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>
Line 188:
next
exit(0)
</syntaxhighlight>
VERSION 2:
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
Line 201:
++i,{argc,i}jle(__CNT_ARGS__)
exit(0)
</syntaxhighlight>
VERSION 3:
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
Line 216:
}
exit(0)
</syntaxhighlight>
VERSION 4:
<syntaxhighlight lang="amazing hopper">
#include <natural.h>
#include <hopper.h>
Line 231:
remember ( argument 'i' ); put a new line and print it; finally increment 'i' ).
exit(0)
</syntaxhighlight>
ETCETERA...
{{out}}
Line 244:
=={{header|AppleScript}}==
<
#!/usr/bin/env osascript
-- Print first argument
Line 250:
return (item 1 of argv)
end run
</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program commandLine.s */
Line 317:
bx lr @ return
</syntaxhighlight>
=={{header|Arturo}}==
<
print a
]</
=={{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). "
<
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\""</
=={{header|AWK}}==
<
BEGIN {
Line 343:
print "Argument " l " is " ARGV[l]
}
}</
=={{header|Babel}}==
Invoke Babel in interactive mode with arguments using the -i switch:
<syntaxhighlight lang
Print the argv list with newlines:
<syntaxhighlight lang
{{out}}
Line 362:
Print the argv list with spaces:
<syntaxhighlight lang
{{out}}
Line 369:
To access an individual argument, use the ith operator to select an element from the argv list; print with newline using say:
<syntaxhighlight lang
{{out}}
Line 380:
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.)
<
Sample output:
Line 389:
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>).
<
PRINT COMMAND$
Line 402:
FOR i = 0 TO __FB_ARGC__ - 1
PRINT "arg "; i; " = '"; *__FB_ARGV__[i]; "'"
NEXT i</
Sample output:
Line 417:
==={{header|BaCon}}===
<
PRINT "Entire command line: ", ARGUMENT$
Line 425:
PRINT " " & cli$[i];
NEXT
PRINT</
{{out}}
Line 440:
=={{header|Batch File}}==
{{works with|Windows NT|4 or later (includes Windows XP and onward)}}
<
setlocal enabledelayedexpansion
Line 454:
for /l %%a in (1,1,%count%) do (
echo !parameter[%%a]!
)</
Another way of doing it
<
@echo off
setlocal enabledelayedexpansion
Line 480:
for /l %%i in (1,1,%p#%) do (
echo p%%i=!p%%i!
)</
Invocation:
<
fn=d:\bin\args2.cmd
p0=args2
Line 492:
p2=bar baz
p3=quux
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang
=={{header|Blue}}==
Line 502:
Linux/x86-64
<
global _start
Line 533:
bye
;
</syntaxhighlight>
=={{header|BQN}}==
BQN has a system value for getting pre-parsed command line arguments.
<syntaxhighlight lang="text">•Show •args</
should show the full list of args.
Line 544:
=={{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)))</
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 576:
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 <stdio.h>
Line 586:
(void) printf("the argument #%d is %s\n", i, argv[i]);
return EXIT_SUCCESS;
}</
=={{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.
<
namespace RosettaCode {
Line 599:
}
}
}</
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.
<
namespace RosettaCode {
Line 612:
}
}
}</
=={{header|C++}}==
Line 619:
This example uses iostream. Traditional C I/O also works.
<
int main(int argc, char* argv[])
Line 629:
return 0;
}</
=={{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).
<
Start = getCommandLine</
=={{header|Clojure}}==
Line 642:
The value of ''*command-line-args*'' is a sequence of the supplied command line arguments, or ''nil'' if none were supplied.
<
=={{header|CLU}}==
Line 652:
Note that unlike C, the program name itself is not included in the list of arguments.
<
% where get_argv lives.
%
Line 665:
stream$putl(po, "arg: " || arg)
end
end start_up</
{{out}}
<pre>$ ./cmdline -c "alpha beta" -h "gamma"
Line 680:
Getting the arguments in one go, exactly as they were passed in:
<
PROGRAM-ID. accept-all-args.
Line 693:
GOBACK
.</
Getting the arguments one at a time, with arguments being split by whitespace if not in quotes:
<
PROGRAM-ID. accept-args-one-at-a-time.
Line 712:
GOBACK
.</
Passing arguments from UNIX/Linux Systems to COBOL.
{{works with|OpenCOBOL}}
{{works with|gnuCOBOL}}
<
*>Created By Zwiegnet 8/19/2004
Line 774:
STOP RUN.
.</
=={{header|CoffeeScript}}==
{{works with|Node.js}}
<
console.log arg for arg in process.argv
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 788:
The following function could be used to create a uniform way to access the arguments:
<
(or
#+clisp (ext:argv)
Line 799:
#+allegro (sys:command-line-arguments)
#+lispworks sys:*line-arguments-list*
nil))</
=={{header|Cowgol}}==
Line 805:
The manner in which arguments are parsed is, however, dependent on the operating system.
<
include "argv.coh";
Line 819:
print(arg);
print("'\n");
end loop;</
{{out}}
Line 838:
=={{header|D}}==
<
import std.stdio;
foreach (immutable i, arg; args[1 .. $])
writefln("#%2d : %s", i + 1, arg);
}</
=={{header|Dart}}==
<
for(var arg in args)
print(arg);
}</
=={{header|DCL}}==
case is not preserved unless the parameter is in quotes
<
$ loop:
$ write sys$output "the value of P''i' is ", p'i
$ i = i + 1
$ if i .le. 8 then $ goto loop</
{{out}}
<pre>$ @command_line_arguments -c "alpha beta" -h "gamma"
Line 871:
=={{header|Delphi}}==
<
// param[0] , so given the axample of myprogram -c "alpha beta" -h "gamma"
Line 884:
// param[3] = -h
// param[4] = gamma
</syntaxhighlight>
=={{header|Déjà Vu}}==
Command line arguments are found in <code>!args</code> and <code>!opts</code>.
<
print\( "Argument #" i " is " )
. get-from !args i
Line 897:
if has !opts :four:
!. get-from !opts :four</
{{out}}
<pre>$ vu args-3.deja one two -c three --four=five
Line 917:
This is however a limitation of the CP/M operating system, and not of Draco.
<
proc nonrec main() void:
Line 927:
writeln(i:3, ": '", par, "'")
od
corp</
{{out}}
Line 940:
=={{header|E}}==
<syntaxhighlight lang
=={{header|Eiffel}}==
Line 946:
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.
<
APPLICATION
inherit
Line 962:
io.read_line -- Keep console window open
end
end</
Output (for command line arguments: -c "alpha beta" -h "gamma"):
Line 972:
=={{header|Elena}}==
ELENA 4.x :
<
import extensions;
Line 979:
program_arguments.forEvery:(int i)
{ console.printLine("Argument ",i," is ",program_arguments[i]) }
}</
{{out}}
<pre>
Line 991:
=={{header|Elixir}}==
Elixir provides command line arguments via the <tt>System.argv()</tt> function.
<
IO.puts 'Arguments:'
Enum.map(System.argv(),&IO.puts(&1))</
Example run:
<
Arguments:
a
b=2
--3
-4</
=={{header|Emacs Lisp}}==
<
(message "Argument: %S" (pop argv)))</
Invoke script:
Line 1,013:
=={{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
result
<
{progname,["erl"]},
{home,["/home/me"]},
{c,["alpha beta"]},
{h,["gamma"]}]</
init:get_argument(name) can be used to fetch value of a particular flag
<
{ok,[["gamma"]]}
5> init:get_argument(c).
{ok,[["alpha beta"]]}</
=={{header|Euphoria}}==
<
printf(1,"Interpreter/executable name: %s\n",{cmd[1]})
printf(1,"Program file name: %s\n",{cmd[2]})
Line 1,037:
printf(1,"#%d : %s\n",{i,cmd[i]})
end for
end if</
=={{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.
<
[<EntryPoint>]
let main args =
Array.iter (fun x -> printfn "%s" x) args
0</
=={{header|Factor}}==
Line 1,052:
=={{header|Fancy}}==
<
a println # print each given command line argument
}</
=={{header|Fantom}}==
<
class Main
{
Line 1,066:
}
}
</syntaxhighlight>
=={{header|Forth}}==
Line 1,072:
{{works with|gforth|0.6.2}}
<
: main
argc @ 0 do i arg type cr loop ;
main bye</
Here is output from a sample run.
<
gforth
args.f
Line 1,085:
beta gamma
delta
$</
=={{header|Fortran}}==
{{works with|Fortran|2003 and later}}
<
implicit none
Line 1,105:
end program command_line_arguments
</syntaxhighlight>
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</
=={{header|FreeBASIC}}==
<
' Program (myprogram.exe) invoke as follows:
Line 1,125:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,133:
=={{header|Free Pascal}}==
<
Program listArguments(input, output, stdErr);
Line 1,145:
End;
End.
</syntaxhighlight>
{{out}}
<pre>
Line 1,158:
=={{header|Frink}}==
Arguments to a program are available in the <CODE>ARGS</CODE> array variable.
<
println[ARGS]
</syntaxhighlight>
=={{header|FunL}}==
<syntaxhighlight lang
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=a1374aa441520314ad0c7decb1e91c97 Click this link to run this code]'''
<
DIM l AS Integer
DIM numparms AS Integer
Line 1,176:
PRINT l; " : "; parm
NEXT
END</
=={{header|Genie}}==
<
/*
Command line arguments, in Genie
Line 1,198:
// to reiterate, args[0] is the command
if args[0] is not null
print "\nWith Genie, args[0] is the command: %s", args[0]</
{{out}}
Line 1,217:
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.
<
=={{header|Go}}==
<syntaxhighlight lang="go">
package main
import (
Line 1,232:
}
}
</syntaxhighlight>
=={{header|Groovy}}==
Command-line arguments are accessible via the '''args''' list variable. The following is saved as the file "Echo.groovy":
<syntaxhighlight lang
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,249:
=={{header|Harbour}}==
Uses the Harbour-specific hb_PValue() function
<
LOCAL i
Line 1,257:
NEXT
RETURN</
=={{header|Haskell}}==
Line 1,264:
myprog.hs:
<
main = getArgs >>= print</
<pre>
myprog a -h b c
Line 1,272:
=={{header|HicEst}}==
<
EDIT(Text=$CMD_LINE, SePaRators='-"', ITeM=i, IF ' ', EXit, ENDIF, Parse=cmd, GetPosition=position)
IF(position > 0) WRITE(Messagebox) cmd
ENDDO</
=={{header|Icon}} and {{header|Unicon}}==
Command line parameters are passed to Icon/Unicon programs as a list of strings.
<
every write(!arglist)
end</
{{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|Ioke}}==
<syntaxhighlight lang
=={{header|J}}==
Line 1,295:
The global <code>ARGV</code> holds the command line arguments. Thus, a program to display them:
<syntaxhighlight lang
In a non-interactive context, we would instead use <code>echo ARGV</code>.
Line 1,301:
=={{header|Java}}==
<
public static void main(String[] args) {
System.out.println("There are " + args.length + " arguments given.");
Line 1,307:
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 [http://commons.apache.org/cli '''Apache Commons CLI'''] (command-line interface) library.
Line 1,313:
=={{header|JavaScript}}==
{{works with|Node.js}}
<
console.log(`${index}: ${val}`);
});</
{{works with|JScript}}
<
for (var i = 0; i < objArgs.length; i++)
WScript.Echo(objArgs.Item(i));</
{{works with|JScript.NET (compiled with jsc.exe)}}
<
var argv:String[] = Environment.GetCommandLineArgs();
for (var i in argv)
print(argv[i]);</
{{works with|Rhino}}
{{works with|SpiderMonkey}}
<
print(arguments[i]);</
=={{header|jq}}==
Line 1,347:
$ jq -n '$ARGS' --args a b
yields:<
"positional": [
"a",
Line 1,353:
],
"named": {}
}</
Arguments specified with ''--args'' are always read as JSON strings; arguments specified with ''--jsonargs''
Line 1,372:
=={{header|Jsish}}==
<
puts(Info.argv0());
puts(console.args);</
{{out}}
Line 1,383:
=={{header|Julia}}==
Works when the Julia program is run as a file argument to julia.exe.
<
prog = Base.basename(Base.source_path())
Line 1,391:
println(" ", s)
end
</syntaxhighlight>
{{out}}
Line 1,408:
per line:
<syntaxhighlight lang="k">
.p'.a
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|Java}}
<
println("There are " + args.size + " arguments given.")
args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") }
}</
{{out}}
See Java output.
=={{header|Lasso}}==
<
iterate($argv) => {
stdoutnl("Argument " + loop_count + ": " + loop_value)
}</
Output:
<
Argument 1: arguments.lasso
Argument 2: -c
Argument 3: alpha beta
Argument 4: -h
Argument 5: gamma</
=={{header|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"
</syntaxhighlight>
Once we're in the shell, we can get all the initializing arguments with this call:
<
> (: init get_arguments)
(#(root ("/opt/erlang/r15b03"))
Line 1,452:
#(c ("alpha beta"))
#(h ("gamma")))
</syntaxhighlight>
We can also get specific arguments if we know their keys:
<
> (: init get_argument 'c)
#(ok (("alpha beta")))
> (: init get_argument 'h)
#(ok (("gamma")))
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang
=={{header|Lingo}}==
<
-- "-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):
{{libheader|CommandLine Xtra}}
<
-- ["-c", "alpha beta", "-h", "gamma"]</
=={{header|Logo}}==
Line 1,480:
logo file.logo - arg1 arg2 arg3
Then the arguments after the "-" are found in a list in variable :COMMAND.LINE
<
[arg1 arg2 arg3]</
Alternatively, make the first line of an executable logo script:
#! /usr/bin/logo -
Line 1,488:
=={{header|LSE64}}==
<
0 # argument
dup arg dup 0 = || ,t 1 + repeat
drop</
=={{header|Lua}}==
Line 1,497:
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 "Arguments:"
for i = 1, #arg do
print( i," ", arg[i] )
end</
=={{header|M2000 Interpreter}}==
Line 1,511:
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">
Module Checkit {
Document a$ = {
Line 1,538:
}
Checkit
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
myprogram:
<
$CommandLine</
Output:
<pre>{myprogram,-c,alpha beta,-h,gamma}</pre>
=={{header|Mercury}}==
<syntaxhighlight lang="text">
:- module cmd_line_args.
:- interface.
Line 1,568:
print_arg(Arg, ArgNum, ArgNum + 1, !IO) :-
io.format("the argument #%d is %s\n", [i(ArgNum), s(Arg)], !IO).
</syntaxhighlight>
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang
=={{header|MMIX}}==
<
argc IS $0
i IS $2
Line 1,597:
TRAP 0,Halt,0
NewLine BYTE #a,0</
=={{header|Modula-2}}==
<
FROM Arguments IMPORT GetArgs, ArgTable, GetEnv;
Line 1,619:
INC (item)
UNTIL item = count
END try.</
Example:
<syntaxhighlight lang="modula-2">
jan@Beryllium:~/modula/test$ try jantje zag eens pruimen hangen
Count = 6
Line 1,630:
4 : pruimen
5 : hangen
</syntaxhighlight>
=={{header|Modula-3}}==
Command line parameters are accessed using the <tt>Params</tt> module.
<
IMPORT IO, Params;
Line 1,645:
END;
END;
END Args.</
Output:
Line 1,662:
=={{header|Nanoquery}}==
{{trans|Ursa}}
<syntaxhighlight lang="nanoquery">//
// command-line arguments
//
Line 1,669:
for i in range(0, len(args) - 1)
println args[i]
end</
{{out}}
<pre>$ java -jar ../nanoquery-2.3_1700.jar -b cmdline.nq "alpha beta" -h "gamma"
Line 1,679:
=={{header|Neko}}==
<
var argc = $asize($loader.args)
Line 1,686:
var arg = 0
while arg < argc $print($loader.args[arg ++= 1], "\n")</
{{out}}
Line 1,698:
=={{header|Nemerle}}==
<
using System.Console;
Line 1,711:
foreach (cl_arg in cl_args) Write($"$cl_arg ");
}
}</
=={{header|NetRexx}}==
In a stand-alone application NetRexx places the command string passed to it in a variable called <tt>arg</tt>.
<
-- sample arguments: -c "alpha beta" -h "gamma"
say "program arguments:" arg
</syntaxhighlight>
'''Output:'''
<pre>
Line 1,725:
=={{header|Nim}}==
<
echo "program name: ", getAppFilename()
echo "Arguments:"
for arg in commandLineParams():
echo arg</
=={{header|Oberon-2}}==
{{works with|oo2c}}
<
MODULE CommandLineArguments;
IMPORT
Line 1,747:
Out.String("4.-: ");Out.String(Args.AsString(4));Out.Ln
END CommandLineArguments.
</syntaxhighlight>
{{out}}
<pre>
Line 1,759:
=={{header|Objeck}}==
<
class Line {
function : Main(args : String[]) ~ Nil {
Line 1,767:
}
}
</syntaxhighlight>
=={{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:
<
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]);
}</
=={{header|OCaml}}==
Line 1,783:
The program name is also passed as "argument", so the array length is actually one more than the number of program arguments.
<
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 [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Arg.html Arg] module ===
<
let somebool = ref false
let somestr = ref ""
Line 1,812:
Printf.printf " %b %d '%s'\n" !somebool !someint !somestr;
;;</
Line 1,835:
The first argument is the program name, so this list is never empty.
<syntaxhighlight lang
=={{header|Oz}}==
===Raw arguments===
Like in C, but without the program name:
<
import Application System
define
Line 1,846:
{ForAll ArgList System.showInfo}
{Application.exit 0}
end</
===Preprocessed arguments===
<
import Application System
define
Line 1,865:
{System.showInfo Args.h}
{Application.exit 0}
end</
=={{header|Pascal}}==
Line 1,874:
@ARGV is the array containing all command line parameters
<
my $params_size = @ARGV;
my $second = $ARGV[1];
my $fifth = $ARGV[4];</
If you don't mind importing a module:
<
GetOptions (
'help|h' => \my $help,
'verbose|v' => \my $verbose,
);</
=={{header|Phix}}==
<!--<
<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>
Line 1,903:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
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.
Line 1,944:
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.
<
$program_name = $argv[0];
$second_arg = $argv[2];
$all_args_without_program_name = array_shift($argv);
</syntaxhighlight>
=={{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.
<
println(ARGS).
main(_) => true.</
{{out}}
Line 1,978:
and then '[http://software-lab.de/doc/refL.html#load load]' all remaining
command line arguments.
<
(de c ()
Line 1,987:
(load T)
(bye)</
Output:
<pre>$ ./myprogram -c "alpha beta" -h "gamma"
Line 1,994:
=={{header|PL/I}}==
<
/* The entire command line except the command word itself is passed */
/* to the parameter variable in PL/I. */
Line 2,003:
end program;
</syntaxhighlight>
=={{header|Pop11}}==
Line 2,009:
variable poparglist contains list of command line arguments (as strings). One can use iteration over list to process then (for example print).
<
for arg in poparglist do
printf(arg, '->%s<-\n');
endfor;</
=={{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:
<
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:
<
? COMMAND$
? COMMAND$(0)
Line 2,026:
PRINT "The argument "; i; " is "; COMMAND$(i)
i = i + 1
LOOP</
=={{header|PowerShell}}==
In PowerShell the arguments to a script can be accessed with the <code>$args</code> array:
<
foreach ($s in $args) {
Write-Host Argument (++$i) is $s
}</
=={{header|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;
</syntaxhighlight>
=={{header|PureBasic}}==
Line 2,049:
===Reading all parameters===
You can easily read all parameters by using ProgramParameter() without argument.
<
Define n=CountProgramParameters()
PrintN("Reading all parameters")
Line 2,059:
Input()
CloseConsole()
EndIf</
===Reading specific parameters===
You can specify which parameter 'n' to read.
<
Define n
PrintN("Reading specific pameters")
Line 2,071:
Input()
CloseConsole()
EndIf</
=={{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:
<
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).
Line 2,091:
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
<
from the commandline, with the following text in <tt>test.r</tt>:
<
args <- (commandArgs(TRUE))
Line 2,112:
}
print(a*2)
print(b*3)</
(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 2,134:
The following is the simplest program that prints the command-line arguments:
<
(current-command-line-arguments)</
You can also explicitly print each argument to standard output:
<
(for ([arg (current-command-line-arguments)]) (displayln arg))</
=={{header|Raku}}==
Line 2,147:
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"
$ raku -e 'sub MAIN($x, $y) { say $x + $y }' 3 5
8
Line 2,154:
$ 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 <code>-e '...'</code>.
=={{header|RapidQ}}==
<
FOR i=1 TO CommandCount
PRINT "The argument "; i; " is "; Command$(i)
NEXT i</
=={{header|Raven}}==
<
stack (6 items)
Line 2,174:
3 => "alpha beta"
4 => "-h"
5 => "gamma"</
=={{header|REALbasic}}==
<
For each arg As String In args
Stdout.WriteLine(arg)
Next
End Function</
Output (given arguments: ''--foo !bar "bat bang"''):
appName.exe
Line 2,190:
=={{header|REXX}}==
The entire command line arguments (as a single string) are passed by REXX to the program.
<
say arg(1)</
Input:
Line 2,199:
only options that start with a minus (-) are to be examined
and assumed to be options.
<
/*another version: */
/* aaa=arg(1) */
Line 2,220:
say
say 'options='opts
say ' data='data</
;Note to users of Microsoft Windows and Regina REXX:
Line 2,283:
=={{header|Ring}}==
<
see copy("=",30) + nl
see "Command Line Parameters" + nl
Line 2,292:
see x + nl
next
</syntaxhighlight>
=={{header|Ruby}}==
Line 2,298:
myprog:
<
p ARGV</
myprog a -h b c
Line 2,305:
=={{header|Rust}}==
<
fn main(){
let args: Vec<_> = env::args().collect();
println!("{:?}", args);
}</
Run:
<syntaxhighlight lang="text">./program -c "alpha beta" -h "gamma"
["./program", "-c", "alpha beta", "-h", "gamma"]</
=={{header|S-lang}}==
The command-line arguments exist in the array __argv:
<
foreach a (__argv)
print(a);
</
__set_argc_argv(new_argv);
Line 2,336:
=={{header|Sather}}==
<
main(args:ARRAY{STR}) is
loop
Line 2,342:
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.
Line 2,361:
array of strings, and returns unit. That array contains the command line arguments.
<
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 <code>argv</code>:
<
=={{header|Scheme}}==
<
(for-each (lambda (arg) (display arg) (newline)) args))</
=={{header|Seed7}}==
<
const proc: main is func
Line 2,386:
writeln("The argument #" <& i <& " is " <& argv(PROGRAM)[i]);
end for;
end func;</
=={{header|Sidef}}==
Command line arguments are available in the ARGV array.
<syntaxhighlight lang
{{out}}
<pre>% myprog -c "alpha beta" -h "gamma"
Line 2,397:
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
(Smalltalk getArgv: i) displayNl
]</
{{works with|Smalltalk/X}}
<
Smalltalk commandLineArguments do:[:each | each printCR]</
=={{header|Standard ML}}==
<
val args = CommandLine.arguments ();
Array.appi
(fn (i, x) => print ("the argument #" ^ Int.toString (i+1) ^ " is " ^ x ^ "\n"))
(Array.fromList args);</
=={{header|Swift}}==
<
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:
{{works with|Swift|1.2+}}
<
println("There are \(Process.argc-1) arguments.")
for i in 1 ..< Int(Process.argc) {
println("the argument #\(i) is \(String.fromCString(Process.unsafeArgv[i])!)")
}</
{{works with|Swift|1.0-1.1}}
<
println("There are \(C_ARGC-1) arguments.")
for i in 1 ..< Int(C_ARGC) {
println("the argument #\(i) is \(String.fromCString(C_ARGV[i])!)")
}</
=={{header|Tailspin}}==
<
$ARGS -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 2,454:
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:
<
puts [lindex $argv 1]
}</
(Tcl counts from zero, thus <tt>[lindex $list 1]</tt> retrieves the second item in the list)
Line 2,466:
number of arguments is provided by #args.
<
[ dup . char: = emit space ] is #=
1 #args [ i #= show-arg ] countedLoop</
=={{header|TXR}}==
Line 2,476:
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.
<
@(collect)
@arg
Line 2,482:
@(output)
My args are: {@(rep)@arg, @(last)@arg@(end)}
@(end)</
<pre>$ ./txr args.txr
Line 2,495:
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.
<
((a b c) (put-line "got three args, thanks!"))
(else (put-line `usage: @(ldiff *full-args* *args*) <arg1> <arg2> <arg3>`)))</
{{out}}
<pre>$ txr command-line-args.txr 1 2
Line 2,509:
===[[Bourne Shell]]===
To retrieve the entire list of arguments:
<
To retrieve the second and fifth arguments:
<
FIFTH=$5</
=={{header|Ursa}}==
In Ursa, all command line arguments (including the program name as invoked) are contained in the string stream args.
<
# command-line arguments
#
Line 2,523:
for (decl int i) (< i (size args)) (inc i)
out args<i> endl console
end for</
Sample shell session in the Bourne shell:
Line 2,538:
This example application does nothing but display the data
structure on standard output.
<
#executable ('parameterized','')
clarg = <.file$[contents: --<''>+ _option%LP]>+ ~command.options</
Here is a bash terminal session.
<pre>$ clarg -c alpha,beta -h gamma --foo=bar,baz
Line 2,563:
args.v
<
./args.v a b c
=[args.v a b c]</
=={{header|vbScript}}==
<
'Command line arguments can be accessed all together by
Line 2,588:
Wscript.Echo "arg=", arg
Next
</syntaxhighlight>
=={{header|Visual Basic}}==
Like [[#BASIC|Qbasic]], Visual Basic returns all of the args in the built-in variable <code>Command$</code>:
<
MsgBox Command$
End Sub</
=={{header|Visual Basic .NET}}==
Line 2,601:
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.
<
For Each token In args
Console.WriteLine(token)
Next
End Sub</
=={{header|Vlang}}==
This assumes that the following script, myscript.v, is run as follows:
$ v run myscript.v -c "alpha beta" -h "gamma"
<
fn main() {
Line 2,616:
println("the argument #$i is $x")
}
}</
{{out}}
Line 2,629:
This assumes that the following script, myscript.wren, is run as follows:
$ wren myscript.wren -c "alpha beta" -h "gamma"
<
System.print(Process.arguments)</
{{out}}
Line 2,641:
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.
<
[loop [C:= ChIn(8);
if C = \EOF\$1A then quit;
Line 2,647:
];
CrLf(0);
]</
{{out}}
Line 2,656:
=={{header|zkl}}==
File myprogram.zkl:
<
vm.arglist.println();</
zkl myprogram -c "alpha beta" -h "gamma"
{{out}}
|