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

let "number += 1"<br />

fi<br />

done<br />

if [ "$number" −eq "$ONE" ]<br />

then<br />

echo "$number file renamed."<br />

else<br />

echo "$number files renamed."<br />

fi<br />

# For correct grammar.<br />

exit 0<br />

# Exercises:<br />

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

# What type of files will this not work on?<br />

# How can this be fixed?<br />

#<br />

# Rewrite this script to process all the files in a directory<br />

#+ containing spaces in their names, and to rename them,<br />

#+ substituting an underscore for each space.<br />

Example A−4. blank−rename: renames filenames containing blanks<br />

This is an even simpler−minded version of previous script.<br />

#! /bin/bash<br />

# blank−rename.sh<br />

#<br />

# Substitutes underscores for blanks in all the filenames in a directory.<br />

ONE=1<br />

number=0<br />

FOUND=0<br />

# For getting singular/plural right (see below).<br />

# Keeps track of how many files actually renamed.<br />

# Successful return value.<br />

for filename in *<br />

#Traverse all files in directory.<br />

do<br />

echo "$filename" | grep −q " "<br />

# Check whether filename<br />

if [ $? −eq $FOUND ]<br />

#+ contains space(s).<br />

then<br />

fname=$filename<br />

# Strip off path.<br />

n=`echo $fname | sed −e "s/ /_/g"` # Substitute underscore for blank.<br />

mv "$fname" "$n"<br />

# Do the actual renaming.<br />

let "number += 1"<br />

fi<br />

done<br />

if [ "$number" −eq "$ONE" ]<br />

then<br />

echo "$number file renamed."<br />

else<br />

echo "$number files renamed."<br />

fi<br />

# For correct grammar.<br />

exit 0<br />

Example A−5. encryptedpw: Uploading to an ftp site, using a locally encrypted password<br />

Appendix A. Contributed Scripts 370

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

Saved successfully!

Ooh no, something went wrong!