tags:

views:

48

answers:

6
test.sh parameter

in test.sh, how can I get the parameter ?

+4  A: 

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
Konrad Rudolph
just curious, how to get the 10th parameter ?
@user198729: Uh … doesn’t my answer already explain that? You `shift` the parameters.
Konrad Rudolph
So there is no general solution? What if I want to get the 100th parameter...
@user198729: this *is* a general solution. If you wanted to get the 100th parameter, you could `shift` 99 times and have the parameter in `$1`.
Konrad Rudolph
`${10}` seems to work, though I'm not sure about compatibility with other shells...
Gordon Davisson
+9  A: 

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 $@

Vinko Vrsalovic
A: 

echo "$@"; prints all parameters

Oliver
+1  A: 

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

See here

Fish
A: 

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.

Dima
A: 

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 "$@"

Dennis Williamson