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.

Chapter 10. Loops and Branches<br />

Operations on code blocks are the key to structured, organized shell scripts. Looping and branching constructs<br />

provide the tools for accomplishing this.<br />

10.1. Loops<br />

A loop is a block of code that iterates (repeats) a list of commands as long as the loop control condition is<br />

true.<br />

for loops<br />

for (in)<br />

This is the basic looping construct. It differs significantly from its C counterpart.<br />

for arg in [list]<br />

do<br />

command(s)...<br />

done<br />

During each pass through the loop, arg takes on the value of each successive variable<br />

in the list.<br />

for arg in "$var1" "$var2" "$var3" ... "$varN"<br />

# In pass 1 of the loop, $arg = $var1<br />

# In pass 2 of the loop, $arg = $var2<br />

# In pass 3 of the loop, $arg = $var3<br />

# ...<br />

# In pass N of the loop, $arg = $varN<br />

# Arguments in [list] quoted to prevent possible word splitting.<br />

The argument list may contain wild cards.<br />

If do is on same line as for, there needs to be a semicolon after list.<br />

for arg in [list] ; do<br />

Example 10−1. Simple for loops<br />

#!/bin/bash<br />

# List the planets.<br />

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

do<br />

echo $planet<br />

done<br />

echo<br />

# Entire 'list' enclosed in quotes creates a single variable.<br />

Chapter 10. Loops and Branches 103

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

Saved successfully!

Ooh no, something went wrong!