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

for a<br />

do<br />

echo −n "$a "<br />

done<br />

# The 'in list' missing, therefore the loop operates on '$@'<br />

#+ (command−line argument list, including whitespace).<br />

echo<br />

exit 0<br />

It is possible to use command substitution to generate the [list] in a for loop. See also Example<br />

12−39, Example 10−10 and Example 12−33.<br />

Example 10−6. Generating the [list] in a for loop with command substitution<br />

#!/bin/bash<br />

# A for−loop with [list] generated by command substitution.<br />

NUMBERS="9 7 3 8 37.53"<br />

for number in `echo $NUMBERS` # for number in 9 7 3 8 37.53<br />

do<br />

echo −n "$number "<br />

done<br />

echo<br />

exit 0<br />

This is a somewhat more complex example of using command substitution to create the [list].<br />

Example 10−7. A grep replacement for binary files<br />

#!/bin/bash<br />

# bin−grep.sh: Locates matching strings in a binary file.<br />

# A "grep" replacement for binary files.<br />

# Similar effect to "grep −a"<br />

E_BADARGS=65<br />

E_NOFILE=66<br />

if [ $# −ne 2 ]<br />

then<br />

echo "Usage: `basename $0` string filename"<br />

exit $E_BADARGS<br />

fi<br />

if [ ! −f "$2" ]<br />

then<br />

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

exit $E_NOFILE<br />

fi<br />

for word in $( strings "$2" | grep "$1" )<br />

Chapter 10. Loops and Branches 106

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

Saved successfully!

Ooh no, something went wrong!