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...

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

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

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

if [ ! −e "$file" ] # Check if file exists.<br />

then<br />

echo "$file does not exist."; echo<br />

continue<br />

# On to next.<br />

fi<br />

ls −l $file | awk '{ print $9 "<br />

whatis `basename $file` # File info.<br />

echo<br />

done<br />

file size: " $5 }' # Print 2 fields.<br />

exit 0<br />

The [list] in a for loop may contain filename globbing, that is, using wildcards for filename<br />

expansion.<br />

Example 10−4. Operating on files with a for loop<br />

#!/bin/bash<br />

# list−glob.sh: Generating [list] in a for−loop using "globbing".<br />

echo<br />

for file in *<br />

do<br />

ls −l "$file" # Lists all files in $PWD (current directory).<br />

# Recall that the wild card character "*" matches every filename,<br />

# however, in "globbing", it doesn't match dot−files.<br />

# If the pattern matches no file, it is expanded to itself.<br />

# To prevent this, set the nullglob option<br />

# (shopt −s nullglob).<br />

# Thanks, S.C.<br />

done<br />

echo; echo<br />

for file in [jx]*<br />

do<br />

rm −f $file # Removes only files beginning with "j" or "x" in $PWD.<br />

echo "Removed file \"$file\"".<br />

done<br />

echo<br />

exit 0<br />

Omitting the in [list] part of a for loop causes the loop to operate on $@, the list of arguments<br />

given on the command line to the script. A particularly clever illustration of this is Example A−17.<br />

Example 10−5. Missing in [list] in a for loop<br />

#!/bin/bash<br />

# Invoke both with and without arguments, and see what happens.<br />

Chapter 10. Loops and Branches 105

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

Saved successfully!

Ooh no, something went wrong!