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.

# The 'd' is the delete command.<br />

# Quoting the command−line arg permits<br />

#+ whitespace and special characters in the filename.<br />

exit 0<br />

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

Example 34−2. A slightly more complex shell wrapper<br />

#!/bin/bash<br />

# "subst", a script that substitutes one pattern for<br />

# another in a file,<br />

# i.e., "subst Smith Jones letter.txt".<br />

ARGS=3<br />

E_BADARGS=65<br />

# Wrong number of arguments passed to script.<br />

if [ $# −ne "$ARGS" ]<br />

# Test number of arguments to script (always a good idea).<br />

then<br />

echo "Usage: `basename $0` old−pattern new−pattern filename"<br />

exit $E_BADARGS<br />

fi<br />

old_pattern=$1<br />

new_pattern=$2<br />

if [ −f "$3" ]<br />

then<br />

file_name=$3<br />

else<br />

echo "File \"$3\" does not exist."<br />

exit $E_BADARGS<br />

fi<br />

# Here is where the heavy work gets done.<br />

sed −e "s/$old_pattern/$new_pattern/g" $file_name<br />

# 's' is, of course, the substitute command in sed,<br />

# and /pattern/ invokes address matching.<br />

# The "g", or global flag causes substitution for *every*<br />

# occurence of $old_pattern on each line, not just the first.<br />

# Read the literature on 'sed' for a more in−depth explanation.<br />

exit 0 # Successful invocation of the script returns 0.<br />

Example 34−3. A shell wrapper around an awk script<br />

#!/bin/bash<br />

# Adds up a specified column (of numbers) in the target file.<br />

ARGS=2<br />

E_WRONGARGS=65<br />

if [ $# −ne "$ARGS" ] # Check for proper no. of command line args.<br />

then<br />

echo "Usage: `basename $0` filename column−number"<br />

Chapter 34. Miscellany 338

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

Saved successfully!

Ooh no, something went wrong!