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.

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

done<br />

# The details, in particular the sleep N, are particular to my<br />

#+ application, but the general pattern is:<br />

while true<br />

do<br />

for job in {pattern}<br />

do<br />

{job already done or running} && continue<br />

{mark job as running, do job, mark job as done}<br />

continue 2<br />

done<br />

break # Or something like `sleep 600' to avoid termination.<br />

done<br />

# This way the script will stop only when there are no more jobs to do<br />

#+ (including jobs that were added during runtime). Through the use<br />

#+ of appropriate lockfiles it can be run on several machines<br />

#+ concurrently without duplication of calculations [which run a couple<br />

#+ of hours in my case, so I really want to avoid this]. Also, as search<br />

#+ always starts again from the beginning, one can encode priorities in<br />

#+ the file names. Of course, one could also do this without `continue 2',<br />

#+ but then one would have to actually check whether or not some job<br />

#+ was done (so that we should immediately look for the next job) or not<br />

#+ (in which case we terminate or sleep for a long time before checking<br />

#+ for a new job).<br />

The continue N construct is difficult to understand and tricky to use in any<br />

meaningful context. It is probably best avoided.<br />

10.4. Testing and Branching<br />

The case and select constructs are technically not loops, since they do not iterate the execution of a code<br />

block. Like loops, however, they direct program flow according to conditions at the top or bottom of the<br />

block.<br />

Controlling program flow in a code block<br />

case (in) / esac<br />

The case construct is the shell equivalent of switch in C/C++. It permits branching to one of a number<br />

of code blocks, depending on condition tests. It serves as a kind of shorthand for multiple if/then/else<br />

statements and is an appropriate tool for creating menus.<br />

case "$variable" in<br />

"$condition1" )<br />

command...<br />

;;<br />

"$condition2" )<br />

command...<br />

;;<br />

Chapter 10. Loops and Branches 117

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

Saved successfully!

Ooh no, something went wrong!