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.

#+ uses the second for a step interval,<br />

#+ and continues until it reaches the third.<br />

do<br />

echo −n "$a "<br />

done # 45 50 55 60 65 70 75 80<br />

echo; echo<br />

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

getopt<br />

exit 0<br />

The getopt command parses command−line options preceded by a dash. This external command<br />

corresponds to the getopts Bash builtin, but it is not nearly as versatile.<br />

Example 12−40. Using getopt to parse command−line options<br />

#!/bin/bash<br />

# Try the following when invoking this script.<br />

# sh ex33a −a<br />

# sh ex33a −abc<br />

# sh ex33a −a −b −c<br />

# sh ex33a −d<br />

# sh ex33a −dXYZ<br />

# sh ex33a −d XYZ<br />

# sh ex33a −abcd<br />

# sh ex33a −abcdZ<br />

# sh ex33a −z<br />

# sh ex33a a<br />

# Explain the results of each of the above.<br />

E_OPTERR=65<br />

if [ "$#" −eq 0 ]<br />

then # Script needs at least one command−line argument.<br />

echo "Usage $0 −[options a,b,c]"<br />

exit $E_OPTERR<br />

fi<br />

set −− `getopt "abcd:" "$@"`<br />

# Sets positional parameters to command−line arguments.<br />

# What happens if you use "$*" instead of "$@"?<br />

while [ ! −z "$1" ]<br />

do<br />

case "$1" in<br />

−a) echo "Option \"a\"";;<br />

−b) echo "Option \"b\"";;<br />

−c) echo "Option \"c\"";;<br />

−d) echo "Option \"d\" $2";;<br />

*) break;;<br />

esac<br />

shift<br />

done<br />

# It is better to use the 'getopts' builtin in a script,<br />

#+ rather than 'getopt'.<br />

# See "ex33.sh".<br />

Chapter 12. External Filters, Programs and Commands 206

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

Saved successfully!

Ooh no, something went wrong!