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 />

a=${param5:+xyz}<br />

echo "a = $a" # a =<br />

# Different result from a=${param5+xyz}<br />

param6=123<br />

a=${param6+xyz}<br />

echo "a = $a" # a = xyz<br />

${parameter?err_msg}, ${parameter:?err_msg}<br />

If parameter set, use it, else print err_msg.<br />

Both forms nearly equivalent. The : makes a difference only when parameter has been declared and is<br />

null, as above.<br />

Example 9−13. Using parameter substitution and error messages<br />

#!/bin/bash<br />

# Check some of the system's environmental variables.<br />

# If, for example, $USER, the name of the person at the console, is not set,<br />

#+ the machine will not recognize you.<br />

: ${HOSTNAME?} ${USER?} ${HOME?} ${MAIL?}<br />

echo<br />

echo "Name of the machine is $HOSTNAME."<br />

echo "You are $USER."<br />

echo "Your home directory is $HOME."<br />

echo "Your mail INBOX is located in $MAIL."<br />

echo<br />

echo "If you are reading this message,"<br />

echo "critical environmental variables have been set."<br />

echo<br />

echo<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# The ${variablename?} construction can also check<br />

#+ for variables set within the script.<br />

ThisVariable=Value−of−ThisVariable<br />

# Note, by the way, that string variables may be set<br />

#+ to characters disallowed in their names.<br />

: ${ThisVariable?}<br />

echo "Value of ThisVariable is $ThisVariable".<br />

echo<br />

echo<br />

: ${ZZXy23AB?"ZZXy23AB has not been set."}<br />

# If ZZXy23AB has not been set,<br />

#+ then the script terminates with an error message.<br />

# You can specify the error message.<br />

# : ${ZZXy23AB?"ZZXy23AB has not been set."}<br />

# Same result with: dummy_variable=${ZZXy23AB?}<br />

# dummy_variable=${ZZXy23AB?"ZXy23AB has not been set."}<br />

#<br />

# echo ${ZZXy23AB?} >/dev/null<br />

Chapter 9. Variables Revisited 86

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

Saved successfully!

Ooh no, something went wrong!