24.07.2018 Views

Bash-Beginners-Guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

9.2.2. Examples<br />

9.2.2.1. Simple example using while<br />

Here is an example for the impatient:<br />

#!/bin/bash<br />

# This script opens 4 terminal windows.<br />

i="0"<br />

while [ $i -lt 4 ]<br />

do<br />

xterm &<br />

i=$[$i+1]<br />

done<br />

9.2.2.2. Nested while loops<br />

The example below was written to copy pictures that are made with a webcam to a web directory. Every five<br />

minutes a picture is taken. Every hour, a new directory is created, holding the images for that hour. Every day,<br />

a new directory is created containing 24 subdirectories. The script runs in the background.<br />

#!/bin/bash<br />

# This script copies files from my homedirectory into the webserver directory.<br />

# (use scp and SSH keys for a remote directory)<br />

# A new directory is created every hour.<br />

PICSDIR=/home/carol/pics<br />

WEBDIR=/var/www/carol/webcam<br />

while true; do<br />

DATE=`date +%Y%m%d`<br />

HOUR=`date +%H`<br />

mkdir $WEBDIR/"$DATE"<br />

while [ $HOUR -ne "00" ]; do<br />

DESTDIR=$WEBDIR/"$DATE"/"$HOUR"<br />

mkdir "$DESTDIR"<br />

mv $PICDIR/*.jpg "$DESTDIR"/<br />

sleep 3600<br />

HOUR=`date +%H`<br />

done<br />

done<br />

Note the use of the true statement. This means: continue execution until we are forcibly interrupted (with kill<br />

or Ctrl+C).<br />

This small script can be used for simulation testing; it generates files:<br />

#!/bin/bash<br />

# This generates a file every 5 minutes<br />

while true; do<br />

Chapter 9. Repetitive tasks 110

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

Saved successfully!

Ooh no, something went wrong!