12.07.2015 Views

Advanced Bash-Scripting Guide

Advanced Bash-Scripting Guide

Advanced Bash-Scripting Guide

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Advanced</strong> <strong>Bash</strong>-<strong>Scripting</strong> <strong>Guide</strong>if [ -n "${10}" ] # Parameters > $9 must be enclosed in {brackets}.thenecho "Parameter #10 is ${10}"fiecho "-----------------------------------"echo "All the command-line parameters are: "$*""if [ $# -lt "$MINPARAMS" ]thenechoecho "This script needs at least $MINPARAMS command-line arguments!"fiechoexit 0Bracket notation for positional parameters leads to a fairly simple way of referencing the lastargument passed to a script on the command line. This also requires indirect referencing.args=$## Number of args passed.lastarg=${!args}# Or: lastarg=${!#}# (Thanks, Chris Monson.)# Note that lastarg=${!$#} doesn't work.Some scripts can perform different operations, depending on which name they are invoked with. Forthis to work, the script needs to check $0, the name it was invoked by. There must also exist symboliclinks to all the alternate names of the script. See Example 15-2.If a script expects a command line parameter but is invoked without one, this maycause a null variable assignment, generally an undesirable result. One way to preventthis is to append an extra character to both sides of the assignment statement using theexpected positional parameter.variable1_=$1_ # Rather than variable1=$1# This will prevent an error, even if positional parameter is absent.critical_argument01=$variable1_# The extra character can be stripped off later, like so.variable1=${variable1_/_/}# Side effects only if $variable1_ begins with an underscore.# This uses one of the parameter substitution templates discussed later.# (Leaving out the replacement pattern results in a deletion.)# A more straightforward way of dealing with this is#+ to simply test whether expected positional parameters have been passed.if [ -z $1 ]thenexit $E_MISSING_POS_PARAMfi# However, as Fabian Kreutz points out,#+ the above method may have unexpected side-effects.# A better method is parameter substitution:# ${1:-$DefaultVal}# See the "Parameter Substition" sectionChapter 4. Introduction to Variables and Parameters 34

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

Saved successfully!

Ooh no, something went wrong!