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.

# Calculate the average of a series of numbers.<br />

SCORE="0"<br />

AVERAGE="0"<br />

SUM="0"<br />

NUM="0"<br />

while true; do<br />

echo -n "Enter your score [0-100%] ('q' for quit): "; read SCORE;<br />

if (("$SCORE" < "0")) || (("$SCORE" > "100")); then<br />

echo "Be serious. Common, try again: "<br />

elif [ "$SCORE" == "q" ]; then<br />

echo "Average rating: $AVERAGE%."<br />

break<br />

else<br />

SUM=$[$SUM + $SCORE]<br />

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

AVERAGE=$[$SUM / $NUM]<br />

fi<br />

done<br />

echo "Exiting."<br />

Note how the variables in the last lines are left unquoted in order to do arithmetic.<br />

9.3. The until loop<br />

9.3.1. What is it?<br />

The until loop is very similar to the while loop, except that the loop executes until the TEST-COMMAND<br />

executes successfully. As long as this command fails, the loop continues. The syntax is the same as for the<br />

while loop:<br />

until TEST-COMMAND; do CONSEQUENT-COMMANDS; done<br />

The return status is the exit status of the last command executed in the CONSEQUENT-COMMANDS list,<br />

or zero if none was executed. TEST-COMMAND can, again, be any command that can exit with a success or<br />

failure status, and CONSEQUENT-COMMANDS can be any UNIX command, script or shell construct.<br />

As we already explained previously, the ";" may be replaced with one or more newlines wherever it appears.<br />

9.3.2. Example<br />

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

An improved picturesort.sh script (see Section 9.2.2.2), which tests for available disk space. If not<br />

enough disk space is available, remove pictures from the previous months:<br />

#!/bin/bash<br />

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

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

# If the pics are taking up too much space, the oldest are removed.<br />

while true; do<br />

Chapter 9. Repetitive tasks 112

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

Saved successfully!

Ooh no, something went wrong!