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

# interactive<br />

...<br />

fi<br />

Alternatively, the script can test for the presence of option "i" in the $− flag.<br />

case $− in<br />

*i*) # interactive shell<br />

;;<br />

*) # non−interactive shell<br />

;;<br />

# (Courtesy of "UNIX F.A.Q.," 1993)<br />

Scripts may be forced to run in interactive mode with the −i option or with a #!/bin/bash −i<br />

header. Be aware that this can cause erratic script behavior or show error messages even when no error is<br />

present.<br />

34.2. Shell Wrappers<br />

A "wrapper" is a shell script that embeds a system command or utility, that saves a set of parameters passed to<br />

that command. Wrapping a script around a complex command line simplifies invoking it. This is expecially<br />

useful with sed and awk.<br />

A sed or awk script would normally be invoked from the command line by a sed −e 'commands' or<br />

awk 'commands'. Embedding such a script in a Bash script permits calling it more simply, and makes it<br />

"reusable". This also enables combining the functionality of sed and awk, for example piping the output of a<br />

set of sed commands to awk. As a saved executable file, you can then repeatedly invoke it in its original form<br />

or modified, without the inconvenience of retyping it on the command line.<br />

Example 34−1. shell wrapper<br />

#!/bin/bash<br />

# This is a simple script that removes blank lines from a file.<br />

# No argument checking.<br />

#<br />

# You might wish to add something like:<br />

# if [ −z "$1" ]<br />

# then<br />

# echo "Usage: `basename $0` target−file"<br />

# exit 65<br />

# fi<br />

# Same as<br />

# sed −e '/^$/d' filename<br />

# invoked from the command line.<br />

sed −e /^$/d "$1"<br />

# The '−e' means an "editing" command follows (optional here).<br />

# '^' is the beginning of line, '$' is the end.<br />

# This match lines with nothing between the beginning and the end,<br />

#+ blank lines.<br />

Chapter 34. Miscellany 337

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

Saved successfully!

Ooh no, something went wrong!