Labels

Friday 26 October 2012

UNIX - All about Positional Parameters

In this article we are going to see about Unix - Positional Parameters. 'Positional Parameters' are none other than 'command-line arguments' in any other languages.

Do remember the special variables before jump into the script:
$0 - Holds the filename or name of the script
$* - All the command line arguments supplied to the script
$@ - It is same as $* but differs when the arguments are explicitly enclosed with quotes
$# - No of arguments passed to the script
$1 - To get the value of first argument
${N} - To get the 'N'th element. For ex, to get 11th parameter, use ${11}
shift - To remove the first element from the argument list 

If you want to practice yourself before writing the shell script, you can run below commands in the shell prompt itself:

$ set one two three four
$ echo $3

three
$ echo $#
4
$ echo $*
one two three four
$ shift
$ echo $*
two three four

Same thing but here you have done it through the script by putting together all commands you were executed previously in the shell prompt:

#!/usr/bin/bash 
echo "No of command line arguments \$#:" $#
echo "Parameters are \$*" $*
echo "Use of '\$@':" $@
echo "File Name \$0: " $0
echo "First parameter is \$1: " $1
echo "To get 10th params \${10}:" ${10}

# To handle Unknown number of parameters
for PARA in $*
do
        echo $PARA
done

Run the script:
$ sh cmdargs.sh one two three four five six seven eight nine ten eleven

Output:
No of command line arguments $#: 11
Parameters are $* one two three four five six seven eight nine ten eleven
Use of '$@': one two three four five six seven eight nine ten eleven
File Name $0:  cmdargs.sh
First parameter is $1:  one
To get 10th params ${10}: ten
one
two
three
four
five
six
seven
eight
nine
ten
eleven

No comments:

Post a Comment