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

# Inspired by a script of John Dubois,<br />

# which was translated into into Bash by Chet Ramey,<br />

# and considerably simplified by Mendel Cooper, author of this document.<br />

for filename in *<br />

# Traverse all files in directory.<br />

do<br />

fname=`basename $filename`<br />

n=`echo $fname | tr A−Z a−z` # Change name to lowercase.<br />

if [ "$fname" != "$n" ] # Rename only files not already lowercase.<br />

then<br />

mv $fname $n<br />

fi<br />

done<br />

exit 0<br />

# Code below this line will not execute because of "exit".<br />

#−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−#<br />

# To run it, delete script above line.<br />

# The above script will not work on filenames containing blanks or newlines.<br />

# Stephane Chazelas therefore suggests the following alternative:<br />

for filename in * # Not necessary to use basename,<br />

# since "*" won't return any file containing "/".<br />

do n=`echo "$filename/" | tr '[:upper:]' '[:lower:]'`<br />

# POSIX char set notation.<br />

# Slash added so that trailing newlines are not<br />

# removed by command substitution.<br />

# Variable substitution:<br />

n=${n%/}<br />

# Removes trailing slash, added above, from filename.<br />

[[ $filename == $n ]] || mv "$filename" "$n"<br />

# Checks if filename already lowercase.<br />

done<br />

exit 0<br />

Example 12−16. du: DOS to UNIX text file conversion.<br />

#!/bin/bash<br />

# du.sh: DOS to UNIX text file converter.<br />

E_WRONGARGS=65<br />

if [ −z "$1" ]<br />

then<br />

echo "Usage: `basename $0` filename−to−convert"<br />

exit $E_WRONGARGS<br />

fi<br />

NEWFILENAME=$1.unx<br />

CR='\015' # Carriage return.<br />

# Lines in a DOS text file end in a CR−LF.<br />

tr −d $CR < $1 > $NEWFILENAME<br />

Chapter 12. External Filters, Programs and Commands 172

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

Saved successfully!

Ooh no, something went wrong!