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

echo "You will not see this message, because script terminated above."<br />

HERE=0<br />

exit $HERE<br />

# Will *not* exit here.<br />

Example 9−14. Parameter substitution and "usage" messages<br />

#!/bin/bash<br />

# usage−message.sh<br />

: ${1?"Usage: $0 ARGUMENT"}<br />

# Script exits here if command−line parameter absent,<br />

#+ with following error message.<br />

# usage−message.sh: 1: Usage: usage−message.sh ARGUMENT<br />

echo "These two lines echo only if command−line parameter given."<br />

echo "command line parameter = \"$1\""<br />

exit 0 # Will exit here only if command−line parameter present.<br />

# Check the exit status, both with and without command−line parameter.<br />

# If command−line parameter present, then "$?" is 0.<br />

# If not, then "$?" is 1.<br />

Parameter substitution and/or expansion. The following expressions are the complement to the match in<br />

expr string operations (see Example 12−6). These particular ones are used mostly in parsing file path names.<br />

Variable length / Substring removal<br />

${#var}<br />

String length (number of characters in $var). For an array, ${#array} is the length of the first<br />

element in the array.<br />

Exceptions:<br />

◊ ${#*} and ${#@} give the number of positional parameters.<br />

◊ For an array, ${#array[*]} and ${#array[@]} give the number of elements in<br />

the array.<br />

Example 9−15. Length of a variable<br />

#!/bin/bash<br />

# length.sh<br />

E_NO_ARGS=65<br />

if [ $# −eq 0 ] # Must have command−line args to demo script.<br />

then<br />

echo "Invoke this script with one or more command−line arguments."<br />

exit $E_NO_ARGS<br />

fi<br />

Chapter 9. Variables Revisited 87

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

Saved successfully!

Ooh no, something went wrong!