Tuesday, January 16, 2007

Special Parameters - BASH beginner


These are the special parameters immensely used in Bash Scripting. Here I am describing the fundamental uses of all of them

$$ :: PID of current shell
$? :: exit status of last executed command
$! :: PID of last background process
$# :: Total number of positional parameters.
$0 :: Name of command being executed.
$* :: List of all shell arguments(can't yield each parameter separately)
$@ :: Same as $*(yields each argument separately when enclosed in double quotes)

Some small scripts to show their uses:

$$ and $0


$ cat apl.sh
#!/bin/sh

tmpfile=/tmp/$0.$$
date >> $tmpfile
cat $tmpfile

$ ./apl.sh
Sat Mar 22 11:08:18 IST 2008

$ cat /tmp/apl.sh.4596
Sat Mar 22 11:08:18 IST 2008

so,
$0 in the script became "apl.sh" (the name of the command i.e. script that got executed)
and
$$=4596 was the PID of the shell where the script got executed.

$?

$ cat exitst.sh
#!/bin/sh

NAME=$1
grep "$NAME" ./names.txt
[ $? == 0 ] && echo "found" || echo "Sorry, not found"

$ ./exitst.sh Alex
Alex Cian
found

$ ./exitst.sh Leo
Sorry, not found


$* and $@
$ cat count1.sh
#!/bin/sh
c=1
while [ "$*" != "" ]
do
echo "$c)$1"
shift
((c+=1))
done

$ ./count1.sh unix bash scripting 1995
1)unix
2)bash
3)scripting
4)1995

Differnece between $@ and $*
Following script will tell you the difference between $@ and $*

$ cat diff.sh
file "$*"
echo "++"
file "$@"

$ ./diff.sh a.txt b.sh
a.txt b.sh: cannot open `a.txt b.sh' (No such file or directory)
++
a.txt: empty
b.sh: Bourne shell script text executable

"$*" can not expand the command line args, so expects for a file name "a.txt b.cpp"
"$@" takes both the file names separately.

$#

$ cat count.sh
#!/bin/sh
c=1
echo "Number of command line args: $#"
tot=$#
while [ $c -le "$tot" ]
do
echo "$c)$1"
((c+=1))
shift
done

$ ./count.sh 12 Alex India
Number of command line args: 3
1)12
2)Alex
3)India

No comments:

© Jadu Saikia www.UNIXCL.com