#!/bin/sh
#Shell script to demonstrate Command Line Arguments
# define variables to be used
i=1
fact=1
# simple loop to use the command line arguments
# Finding the factorial of a number supplied with the
# command line argument $1
while test $1 -ge $i
do
fact=`expr $fact \* $i`
i=`expr $i + 1`
echo $fact
done
echo "The Factorial Of $1 Is: $fact"
Command line arguments can be accessed by using the notation $0, $1, $2 and so on up to $9. Where $0 refers to the command/program name itself while other arguments refer to the command line arguments.
To find count of arguments use $* or $@.
To handle more than 9 command line arguments, use shift operator. See an example below.
while [ #1 -ge 1 ];
do
echo $1
shift
done
shift will shift $2 value to $1, $3 value to $2 and so on. If you want to use all command line arguments in more than one place, store them in an array before calling shift, as the arguments which shifted will not be retrieved again.
$# gives you the positional parameters where as $* will give you all parameters as a single word.