find total number of arguments and access one by one - shell

by rajesh 2008-08-08 12:26:59

it is very simple to find total number of arguments passed to a shell...

just use $#

$# will return the total number of arguments
example:
echo "$#";

To parse and use each argument passed we have use while loop similar to the following code
while [ $# -gt 0 ]
do
echo "$#"

#here you can fetch the argument using $1 as shift at the end of this loop will
#shift the argument position by one up. That is shift will reduce the number
#of arguments by one, every time it is called
echo "I am $1"

shift
sleep 1s
done


example:
>test.sh test1 test2 test3

result:
3
I am test1
2
I am test2
1
I am test3

Tagged in:

2161
like
0
dislike
0
mail
flag

You must LOGIN to add comments