Thursday, 23 January 2014

" $0" Parameter Shell Scripting

$0 is one of the Bash special parameters. It can only be referenced as follows (just an example as there are various ways to reference and use $0 while scripting) :
echo "$0"
echo "Usage: $0 fileName"
However, assignment to it is not allowed:


$0 expands to the name of the shell or shell script. This is set at shell initialization. If bash is invoked with a file of commands, $0 is set to the name of that file. It is often used to display script usage message:
 # if filename not supplied at the command prompt
# display usae message and die
[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; }
echo "Script name: $0"
echo "\$1 = $1, so \$_file set to $1"
# if file not found, display an error and die
[ ! -f "$_file" ] && { echo "$0: $_file file not found."; exit 2; }
# if we are here, means everything is okay
echo "Processing $_file..."
Save and close the file. You can run it as follows:
chmod +x 
Sample outputs:
Usage: ./ filename 
Now, try to pass /etc/passwd filename :
./ /etc/passwd
Sample outputs:
./ /etc/passwd
Script name: ./
$1 = /etc/passwd, so $_file set to /etc/passwd
Processing /etc/passwd...
Finally, try to pass any /nonexistencefile.txt filename :
./ /nonexistencefile.txt
Sample outputs:
Script name: ./
$1 = /nonexistencefile.txt, so $_file set to /nonexistencefile.txt
./ /nonexistencefile.txt file not found.
If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the file name used to invoke bash, as given by argument zero.

0 blogger-disqus:

Post a comment