27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

MINPARAMS=10<br />

echo<br />

echo "The name of this script is \"$0\"."<br />

# Adds ./ for current directory<br />

echo "The name of this script is \"`basename $0`\"."<br />

# Strips out path name info (see 'basename')<br />

echo<br />

if [ −n "$1" ]<br />

# Tested variable is quoted.<br />

then<br />

echo "Parameter #1 is $1" # Need quotes to escape #<br />

fi<br />

if [ −n "$2" ]<br />

then<br />

echo "Parameter #2 is $2"<br />

fi<br />

if [ −n "$3" ]<br />

then<br />

echo "Parameter #3 is $3"<br />

fi<br />

# ...<br />

if [ −n "${10}" ] # Parameters > $9 must be enclosed in {brackets}.<br />

then<br />

echo "Parameter #10 is ${10}"<br />

fi<br />

echo "−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−"<br />

echo "All the command−line parameters are: "$*""<br />

if [ $# −lt "$MINPARAMS" ]<br />

then<br />

echo<br />

echo "Give me at least $MINPARAMS command−line arguments!"<br />

fi<br />

echo<br />

exit 0<br />

The bracket notation for positional parameters leads to a fairly simply way of referencing the last<br />

argument passed to a script on the command line. This also requires indirect referencing.<br />

args=$#<br />

# Number of args passed.<br />

lastarg=${!args} # Note that lastarg=${!$#} doesn't work.<br />

Some scripts can perform different operations, depending on which name they are invoked with. For<br />

this to work, the script needs to check $0, the name it was invoked by. There must also exist symbolic<br />

links to all the alternate names of the script.<br />

If a script expects a command line parameter but is invoked without one, this may<br />

cause a null variable assignment, generally an undesirable result. One way to prevent<br />

Chapter 4. Introduction to Variables and Parameters 29

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!