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

m4<br />

exit 0<br />

A hidden treasure, m4 is a powerful macro processing filter, [37] virtually a complete language.<br />

Although originally written as a pre−processor for RatFor, m4 turned out to be useful as a<br />

stand−alone utility. In fact, m4 combines some of the functionality of eval, tr, and awk, in addition to<br />

its extensive macro expansion facilities.<br />

The April, 2002 issue of Linux Journal has a very nice article on m4 and its uses.<br />

Example 12−45. Using m4<br />

doexec<br />

#!/bin/bash<br />

# m4.sh: Using the m4 macro processor<br />

# Strings<br />

string=abcdA01<br />

echo "len($string)" | m4 # 7<br />

echo "substr($string,4)" | m4<br />

# A01<br />

echo "regexp($string,[0−1][0−1],\&Z)" | m4<br />

# 01Z<br />

# Arithmetic<br />

echo "incr(22)" | m4 # 23<br />

echo "eval(99 / 3)" | m4 # 33<br />

exit 0<br />

The doexec command enables passing an arbitrary list of arguments to a binary executable. In<br />

particular, passing argv[0] (which corresponds to $0 in a script) lets the executable be invoked by<br />

various names, and it can then carry out different sets of actions, according to the name by which it<br />

was called. What this amounts to is roundabout way of passing options to an executable.<br />

For example, the /usr/local/bin directory might contain a binary called "aaa". Invoking doexec<br />

/usr/local/bin/aaa list would list all those files in the current working directory beginning with an "a",<br />

while invoking (the same executable with) doexec /usr/local/bin/aaa delete would delete those files.<br />

The various behaviors of the executable must be defined<br />

within the code of the executable itself, analogous to<br />

something like the following in a shell script:<br />

case `basename $0` in<br />

"name1" ) do_something;;<br />

"name2" ) do_something_else;;<br />

"name3" ) do_yet_another_thing;;<br />

* ) bail_out;;<br />

esac<br />

Chapter 12. External Filters, Programs and Commands 213

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

Saved successfully!

Ooh no, something went wrong!