test.sh parameter
in test.sh
, how can I get the parameter ?
test.sh parameter
in test.sh
, how can I get the parameter ?
By accessing $0
through $9
($0
being the script name). Alternatively, $*
returns the list of all parameters.
If you want to access the parameters one after another, or if you want to access parameters beyond the 9th, you can shift
the parameters:
echo $1
shift
echo $1
When called like this:
./script.sh foo bar
will produce:
foo
bar
If it's a single parameter you use $1
(and $2
and so on, $0
is the script name). Then, to get ALL parameters you use $@
Each argument is accessed by $NUM where NUM is the number of argument you wish to access. $0 is a special argument indicating the name of the script. $# returns the number of arguments.
test.sh alpha beta gamma
echo $0
echo $1
echo $2
echo $3
echo $#
Will give
test.sh
alpha
beta
gamma
3
You can also use shift
to "shift" through parameters. $1
contains the first parameter. If you call shift
then the second parameter will be "shifted" into $1
, and so on.
At least in Bash, you can do either of these to access any parameter, including 10 and beyond:
echo "${10}"
echo "${@:10:1}"
To iterate over all the parameters:
for arg
do
echo "$arg"
done
That form implies for arg in "$@"