[manual index][section index]


arg - shell command-line argument parsing


load arg
arg [ opts command ]... - args


Arg is a loadable module for sh(1) that parses command-line arguments in the same form as arg(2). It accepts a list of (optscommand) pairs, where each character in opts is an acceptable option, and command is a shell command to be run if any character in opts is found. Any trailing plus (+) characters in opts cause arg to extract the same number of arguments associated with the option before running command. For the duration of command, the environment variable $opt will be set to the option that has been found, and $arg will be set to the option's arguments (if the correct number of arguments have been extracted; otherwise a message will be printed, and a usage exception raised). The option character asterisk (*) matches any option letter (this must be quoted, to avoid the usual special interpretation by the shell). Only one command will be run for any option found; if there is no matching option letter, then a default error message will be printed, and a usage exception raised.

The list of option specifications is terminated with a single minus (-); the arguments to be parsed follow this. When the argument parsing has finished the environment variable $* is set to the remaining list of arguments.


The following shell script, script, takes options b, c and f, where f takes a file name argument.
load arg
bflag := cflag := 0
file  := ()
args  := $*
    bc  {$opt^flag = 1}
    f+  {file=$arg}
    r++++ {rect=$arg}
    '*' {echo unknown option $opt}
    - $args
echo $0 $bflag $cflag $file
echo rect $rect
echo arguments are $*

When invoked as follows:

script -bc -r 0 10 50 100 -ffile a b c

the output is:

./script 1 1 file
rect 0 10 50 100
arguments are a b c

and when invoked by:

script -b -f file -z -- -bc

the output is:

unknown option z
./script 1 0 file
arguments are -bc




sh(1), arg(2), sh-std(1)

SH-ARG(1 ) Rev:  Tue Mar 31 02:42:38 GMT 2015