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

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−Scripting</strong> <strong>Guide</strong><br />

#!/bin/bash<br />

# 'getopts' processes command line arguments to script.<br />

# The arguments are parsed as "options" (flags) and associated arguments.<br />

# Try invoking this script with<br />

# 'scriptname −mn'<br />

# 'scriptname −oq qOption' (qOption can be some arbitrary string.)<br />

# 'scriptname −qXXX −r'<br />

#<br />

# 'scriptname −qr' − Unexpected result, takes "r" as the argument to option "q"<br />

# 'scriptname −q −r' − Unexpected result, same as above<br />

# If an option expects an argument ("flag:"), then it will grab<br />

# whatever is next on the command line.<br />

NO_ARGS=0<br />

E_OPTERROR=65<br />

if [ $# −eq "$NO_ARGS" ] # Script invoked with no command−line args?<br />

then<br />

echo "Usage: `basename $0` options (−mnopqrs)"<br />

exit $E_OPTERROR # Exit and explain usage, if no argument(s) given.<br />

fi<br />

# Usage: scriptname −options<br />

# Note: dash (−) necessary<br />

while getopts ":mnopq:rs" Option<br />

do<br />

case $Option in<br />

m ) echo "Scenario #1: option −m−";;<br />

n | o ) echo "Scenario #2: option −$Option−";;<br />

p ) echo "Scenario #3: option −p−";;<br />

q ) echo "Scenario #4: option −q−, with argument \"$OPTARG\"";;<br />

# Note that option 'q' must have an associated argument,<br />

# otherwise it falls through to the default.<br />

r | s ) echo "Scenario #5: option −$Option−"'';;<br />

* ) echo "Unimplemented option chosen.";; # DEFAULT<br />

esac<br />

done<br />

shift $(($OPTIND − 1))<br />

# Decrements the argument pointer so it points to next argument.<br />

exit 0<br />

Script Behavior<br />

source, . (dot command)<br />

This command, when invoked from the command line, executes a script. Within a script, a source<br />

file−name loads the file file−name. This is the shell scripting equivalent of a C/C++<br />

#include directive. It is useful in situations when multiple scripts use a common data file or<br />

function library.<br />

Example 11−18. "Including" a data file<br />

#!/bin/bash<br />

Chapter 11. Internal Commands and Builtins 139

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

Saved successfully!

Ooh no, something went wrong!