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.

4.<br />

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

sh −x scriptname echoes the result each command, but in an abbreviated manner. This is the<br />

equivalent of inserting set −x or set −o xtrace in the script.<br />

Inserting set −u or set −o nounset in the script runs it, but gives an unbound variable error<br />

message at each attempt to use an undeclared variable.<br />

Using an "assert" function to test a variable or condition at critical points in a script. (This is an idea<br />

borrowed from C.)<br />

Example 30−4. Testing a condition with an "assert"<br />

#!/bin/bash<br />

# assert.sh<br />

assert ()<br />

# If condition false,<br />

{ #+ exit from script with error message.<br />

E_PARAM_ERR=98<br />

E_ASSERT_FAILED=99<br />

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

then<br />

return $E_PARAM_ERR<br />

fi<br />

# Not enough parameters passed.<br />

# No damage done.<br />

}<br />

lineno=$2<br />

if [ ! $1 ]<br />

then<br />

echo "Assertion failed: \"$1\""<br />

echo "File \"$0\", line $lineno"<br />

exit $E_ASSERT_FAILED<br />

# else<br />

# return<br />

# and continue executing script.<br />

fi<br />

a=5<br />

b=4<br />

condition="$a −lt $b"<br />

# Error message and exit from script.<br />

# Try setting "condition" to something else,<br />

#+ and see what happens.<br />

assert "$condition" $LINENO<br />

# The remainder of the script executes only if the "assert" does not fail.<br />

# Some commands.<br />

# ...<br />

echo "This statement echoes only if the \"assert\" does not fail."<br />

# ...<br />

# Some more commands.<br />

exit 0<br />

5. trapping at exit.<br />

The exit command in a script triggers a signal 0, terminating the process, that is, the script itself. [61]<br />

It is often useful to trap the exit, forcing a "printout" of variables, for example. The trap must be the<br />

Chapter 30. Debugging 321

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

Saved successfully!

Ooh no, something went wrong!