24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

9.5.3. Examples<br />

In the following example, file names are converted to lower case. If no conversion needs to be done, a<br />

continue statement restarts execution of the loop. These commands don't eat much system resources, and<br />

most likely, similar problems can be solved using sed and awk. However, it is useful to know about this kind<br />

of construction when executing heavy jobs, that might not even be necessary when tests are inserted at the<br />

correct locations in a script, sparing system resources.<br />

[carol@octarine ~/test] cat tolower.sh<br />

#!/bin/bash<br />

# This script converts all file names containing upper case characters into file# names containin<br />

LIST="$(ls)"<br />

for name in "$LIST"; do<br />

if [[ "$name" != *[[:upper:]]* ]]; then<br />

continue<br />

fi<br />

ORIG="$name"<br />

NEW=`echo $name | tr 'A-Z' 'a-z'`<br />

mv "$ORIG" "$NEW"<br />

echo "new name for $ORIG is $NEW"<br />

done<br />

This script has at least one disadvantage: it overwrites existing files. The noclobber option to <strong>Bash</strong> is only<br />

useful when redirection occurs. The -b option to the mv command provides more security, but is only safe in<br />

case of one accidental overwrite, as is demonstrated in this test:<br />

[carol@octarine ~/test] rm *<br />

[carol@octarine ~/test] touch test Test TEST<br />

[carol@octarine ~/test] bash -x tolower.sh<br />

++ ls<br />

+ LIST=test<br />

Test<br />

TEST<br />

+ [[ test != *[[:upper:]]* ]]<br />

+ continue<br />

+ [[ Test != *[[:upper:]]* ]]<br />

+ ORIG=Test<br />

++ echo Test<br />

++ tr A-Z a-z<br />

+ NEW=test<br />

+ mv -b Test test<br />

+ echo 'new name for Test is test'<br />

new name for Test is test<br />

+ [[ TEST != *[[:upper:]]* ]]<br />

+ ORIG=TEST<br />

++ echo TEST<br />

++ tr A-Z a-z<br />

+ NEW=test<br />

+ mv -b TEST test<br />

+ echo 'new name for TEST is test'<br />

new name for TEST is test<br />

Chapter 9. Repetitive tasks 116

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

Saved successfully!

Ooh no, something went wrong!