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.

for planet in "Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto"<br />

do<br />

echo $planet<br />

done<br />

exit 0<br />

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

Each [list] element may contain multiple parameters. This is useful when<br />

processing parameters in groups. In such cases, use the set command (see Example<br />

11−13) to force parsing of each [list] element and assignment of each component<br />

to the positional parameters.<br />

Example 10−2. for loop with two parameters in each [list] element<br />

#!/bin/bash<br />

# Planets revisited.<br />

# Associate the name of each planet with its distance from the sun.<br />

for planet in "Mercury 36" "Venus 67" "Earth 93" "Mars 142" "Jupiter 483"<br />

do<br />

set −− $planet # Parses variable "planet" and sets positional parameters.<br />

# the "−−" prevents nasty surprises if $planet is null or begins with a dash.<br />

# May need to save original positional parameters, since they get overwritten.<br />

# One way of doing this is to use an array,<br />

# original_params=("$@")<br />

echo "$1<br />

$2,000,000 miles from the sun"<br />

#−−−−−−−two tabs−−−concatenate zeroes onto parameter $2<br />

done<br />

# (Thanks, S.C., for additional clarification.)<br />

exit 0<br />

A variable may supply the [list] in a for loop.<br />

Example 10−3. Fileinfo: operating on a file list contained in a variable<br />

#!/bin/bash<br />

# fileinfo.sh<br />

FILES="/usr/sbin/privatepw<br />

/usr/sbin/pwck<br />

/usr/sbin/go500gw<br />

/usr/bin/fakefile<br />

/sbin/mkreiserfs<br />

/sbin/ypbind"<br />

echo<br />

for file in $FILES<br />

do<br />

# List of files you are curious about.<br />

# Threw in a dummy file, /usr/bin/fakefile.<br />

Chapter 10. Loops and Branches 104

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

Saved successfully!

Ooh no, something went wrong!