Subscribe to How-To Geek

The Art of Shell Scripting

People sometimes ask me how I come up with the useful shell scripts that I use on a daily basis to do everything from uploading files to automating backup jobs or setting gmail as the default mail client in ubuntu.

It's simple - when I need help, I turn to the advanced bash-scripting guide, pretty much the best resource a geek can find on the art of shell scripting. Here's an example of a script from the site that renames files with spaces containing blanks to use underscores instead. [source]

#! /bin/bash
# blank-rename.sh
#
# Substitutes underscores for blanks in all
# the filenames in a directory.

ONE=1        # For getting singular/plural right (see below).
number=0     # Keeps track of how many files actually renamed.
FOUND=0      # Successful return value.

for filename in *         #Traverse all files in directory.
do
     echo "$filename" | grep -q " "    #  Check whether filename
     if [ $? -eq $FOUND ]              #+ contains space(s).
     then
       fname=$filename         # Yes, this filename needs work.
       n=`echo $fname | sed -e "s/ /_/g"` # Substitute underscore
                                          # for blank.
       mv "$fname" "$n"                   # Do the actual renaming.
       let "number += 1"
     fi
done   

if [ "$number" -eq "$ONE" ]                 # For correct grammar.
then
 echo "$number file renamed."
else
 echo "$number files renamed."
fi 

exit 0

There's all sorts of good stuff there, you really need to check it out.

Advanced Bash-Scripting Guide

| More
This article was originally written on 06/18/07 Tagged with: Linux

Daily Email Updates

You can get our how-to articles in your inbox each day for free. Just enter your name and email below:


Name:
Email:

Leave a Comment




Leave your friendly comment here.

If you have a computer help question, click here to leave it on the forums instead.

Note: Your comment may not show up immediately on the site.

Our Friends
Getting Started


About How-To Geek
What Is That Process?
svchost.exe
jusched.exe
dwm.exe
ctfmon.exe
wmpnetwk.exe
mDNSResponder.exe
wmpnscfg.exe
rundll32.exe
wfcrun32.exe
Ipoint.exe
Itype.exe
Wfica32.exe
Mobsync.exe
conhost.exe
Dpupdchk.exe Adobe_Updater.exe

Copyright © 2006-2009 HowToGeek.com. All Rights Reserved.