Command-line arguments

From Rosetta Code
Revision as of 15:53, 5 June 2009 by rosettacode>Briantrice (Slate implementation)
Task
Command-line arguments
You are encouraged to solve this task according to the task description, using any language you may know.

Retrieve the list of command-line arguments given to the program.

Example command line:

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

Ada

Command line arguments are available through the predefined package Ada.Command_Line.

<lang ada>with Ada.Command_line; use Ada.Command_Line; with Ada.Text_IO; use Ada.Text_IO

procedure Print_Commands is begin

  -- The number of command line arguments is retrieved from the function Argument_Count
  -- The actual arguments are retrieved from the function Argument
  -- The program name is retrieved from the function Command_Name
  Put(Command_Name & " ");
  for Arg in 1..Argument_Count loop
     Put(Argument(Arg) & " ");
  end loop;
  New_Line;

end Print_Commands;</lang>

ALGOL 68

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386 - argc and argv are not part of the standard's prelude

<lang algol>main:(

 FOR i TO argc DO
   printf(($"the argument #"g(-0)" is "gl$, i, argv(i)))
 OD

)</lang> Output:

the argument #1 is a68g
the argument #2 is Command_Line_Arguments.a68

AutoHotkey

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

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\""</lang>

BASIC

Works with: FreeBASIC

<lang freebasic>DIM i AS Integer

PRINT "This program is named "; Command$(0) i = 1 DO WHILE(LEN(Command$(i)))

   PRINT "The argument "; i; " is "; Command$(i)
   i = i+1

LOOP</lang>

See also: RapidQ

C

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

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

<lang c>#include <stdio.h>

int main(int argc, char* argv[]) {

 int i;
 printf("This program is named %s.\n", argv[0]);
 for (i = 1; i < argc; ++i)
   printf("the argument #%d is %s\n", i, argv[i]);

}</lang>

C++

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

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

<lang cpp>#include <iostream>

int main(int argc, char* argv[]) {

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

}</lang>

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. <lang csharp>using System;

namespace RosettaCode {

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

}</lang>

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. <lang csharp>using System;

namespace RosettaCode {

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

}</lang>

Clean

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

import ArgEnv

Start = getCommandLine

D

<lang d>import std.stdio ;

void main(string[] args) {

 foreach(i, e ; args[1..$])
   writefln("#%2d : %s", i + 1, e) ;

}</lang>

DOS Batch File

@if not [%1]==[] echo %~1 & call %0 %2 %3 %4 %5 %6 %7 %8 %9

E

interp.getArgs()

Erlang

3> init:get_arguments().

result

[{root,["/usr/erlang/erl5.5"]},
{progname,["erl"]},
{home,["/home/me"]},
{c,["alpha beta"]},
{h,["gamma"]}]

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

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

Forth

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

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

main bye

Here is output from a sample run.

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

Groovy

Command-line arguments are accessible via the args list variable. The following is saved as the file "Echo.groovy": <lang groovy>println args</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:

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

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

Haskell

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

myprog.hs: <lang haskell>import System main = getArgs >>= print</lang>

myprog a -h b c
=> ["a","-h","b","c"]

J

The global ARGV holds the command line arguments.

Java

<lang java>public class Arguments {

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

}</lang>

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

Works with: UCB Logo version 5.6

If the command line to a logo script is written

logo file.logo - arg1 arg2 arg3

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

show :COMMAND.LINE
[arg1 arg2 arg3]

</lang> Alternatively, make the first line of an executable logo script:

#! /usr/bin/logo -

to be able to invoke the script with arguments.

file.logo arg1 arg2 arg3

LSE64

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

Modula-3

Command line parameters are accessed using the Params module. <lang modula3>MODULE Args EXPORTS Main;

IMPORT IO, Params;

BEGIN

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

END Args.</lang>

Output:

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

OCaml

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

<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</lang>

Using the Arg module

<lang ocaml>(* default values *) let somebool = ref false let somestr = ref "" let someint = ref 0

let usage = "usage: " ^ Sys.argv.(0) ^ " [-b] [-s string] [-d int]"

let speclist = [

   ("-b", Arg.Unit   (fun () -> somebool := true), ": set somebool to true");
   ("-s", Arg.String (fun s -> somestr := s),      ": what follows -s sets some string");
   ("-d", Arg.Int    (fun d -> someint := d),      ": some int parameter");
 ]

let () =

 (* Read the arguments *)
 Arg.parse
   speclist
   (fun x -> raise (Arg.Bad ("Bad argument : " ^ x)))
   usage;
 Printf.printf " %b %d '%s'\n" !somebool !someint !somestr;
</lang>


% ocaml arg.ml --help
usage: tmp.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

% ocaml arg.ml -d 4 -b -s blabla
 true 4 'blabla'

% ocaml arg.ml
 false 0 ''

Perl

Works with: Perl version 5.x

@ARGV is the array containing all command line parameters

<lang perl>my @params = @ARGV; my $second = $ARGV[1]; my $fifth = $ARGV[4];</lang>

PHP

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

<lang php><?php $program_name = $argv[0]; $second_arg = $argv[2]; ?></lang>

Pop11

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

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

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:

<lang python>import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)</lang>

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

RapidQ

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

Raven

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

Ruby

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

myprog: <lang ruby>#! /usr/bin/env ruby p ARGV</lang>

 myprog a -h b c
 => ["a","-h","b","c"]

Scheme

Works with: Chicken Scheme

COMMAND-LINE-ARGUMENTS returns a list of the arguments.

martin@thinkpad:~$ csi -e "(display (command-line-arguments)) (newline)"
(-e (display (command-line-arguments)) (newline))

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 local
   var integer: i is 0;
 begin
   writeln("This program is named " <& name(PROGRAM) <& ".");
   for i range 1 to length(argv(PROGRAM)) do
     writeln("The argument #" <& i <& " is " <& argv(PROGRAM)[i]);
   end for;
 end func;</lang>

Slate

<lang slate> StartupArguments do: [| :arg | inform: arg] </lang>

Smalltalk

Works with: GNU Smalltalk

<lang smalltalk>(1 to: Smalltalk getArgc) do: [ :i |

 (Smalltalk getArgv: i) displayNl

]</lang>

Standard ML

<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);</lang>

Tcl

The predefined variable argc contains the number of arguments passed to the routine, argv contains the arguments as a list. Retrieving the second argument might look something like this:

<lang tcl>if { $argc > 1 } {

   puts [lindex $argv 1]

}</lang>

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

Toka

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

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

UNIX Shell

Bourne Shell

To retrieve the entire list of arguments:

WHOLELIST="$@"

To retrieve the second and fifth arguments:

SECOND=$2
FIFTH=$5


V

The arguments to the program are stored in the stack,

args.v

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

Visual Basic .NET

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

<lang vb> Sub Main(ByVal args As String())

       For Each token In args
           Console.WriteLine(token)
       Next
   End Sub</lang>