Passing arguments is the easiest of the two (see "What are special dollar sign shell variables?" on SO):
#!/bin/sh
echo "$#"; # total number of arguments
echo "$0"; # name of the shell script
echo "$1"; # first argument
Assuming the file is named "stuff" (sans an extension) and the result of running ./stuff hello world
:
3
stuff
hello
To pass in single letter switches (w/ optional associated params), e.g. ./stuff -v -s hello
you'll want to use getopts
. See "How do you use getopts" on SO and this great tutorial. Here is an example:
#!/bin/sh
verbose=1
string=
while getopts ":vs:" OPT; do
case "$OPT" in
v) verbose=0;;
s) string="$OPTARG";;
esac;
done;
if verbose; then
echo "verbose is on";
fi;
echo "$string";
The line having getopts
coupled with while
needs further explanation:
while
- start the while loop, going through everything getopts
returns back after it processes
getopts :vs: OPT;
- the program getopts
with 2 arguments :vs:
and OPT
getopts
- returns something while
can iterate over
:vs:
- the first argument, this describes what switches getopts
will look for while it parses the shell line
:
- the first colon takes getopts
out of debug mode, omit this to make getopts
verbose
v
- find the switch -v
, this will not have an argument after it, just a simple switch
s:
- find the option -s
with an argument after it
OPT
- will store the character used (the name of the switch), e.g. "v" or "s"
OPTARG
- the variable to load the value into during each of while
's iterations. For v
, $OPTARG
will not have a value, but for s
it will.
The colon :
tells getopts to look for an argument after the switch. The only exception is if the sequence of characters starts with :
then it toggles getopts
in/out of debug/verbose mode. For example:
getopts :q:r:stu:v
will take getopts out of debug mode, will tell it that switches q
, r
, and u
will expects args, while s
, t
, and u
won't. This would be applicable for something like: stuff -q hello -r world -s -t -u 123 -v
getopts tuv
will only tell getopts to search for switches t
, u
and v
with no arguments, e.g. stuff -t -u -v
, and to be verbose