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

#!/bin/bash<br />

# Delete filenames in current directory containing bad characters.<br />

for filename in *<br />

do<br />

badname=`echo "$filename" | sed −n /[\+\{\;\"\\\=\?~\(\)\\&\*\|\$]/p`<br />

# Files containing those nasties: + { ; " \ = ? ~ ( ) < > & * | $<br />

rm $badname 2>/dev/null # So error messages deep−sixed.<br />

done<br />

# Now, take care of files containing all manner of whitespace.<br />

find . −name "* *" −exec rm −f {} \;<br />

# The path name of the file that "find" finds replaces the "{}".<br />

# The '\' ensures that the ';' is interpreted literally, as end of command.<br />

exit 0<br />

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

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

# An alternative to the above script:<br />

find . −name '*[+{;"\\=?~()&*|$ ]*' −exec rm −f '{}' \;<br />

exit 0<br />

# (Thanks, S.C.)<br />

Example 12−3. Deleting a file by its inode number<br />

#!/bin/bash<br />

# idelete.sh: Deleting a file by its inode number.<br />

# This is useful when a filename starts with an illegal character,<br />

#+ such as ? or −.<br />

ARGCOUNT=1<br />

E_WRONGARGS=70<br />

E_FILE_NOT_EXIST=71<br />

E_CHANGED_MIND=72<br />

# Filename arg must be passed to script.<br />

if [ $# −ne "$ARGCOUNT" ]<br />

then<br />

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

exit $E_WRONGARGS<br />

fi<br />

if [ ! −e "$1" ]<br />

then<br />

echo "File \""$1"\" does not exist."<br />

exit $E_FILE_NOT_EXIST<br />

fi<br />

inum=`ls −i | grep "$1" | awk '{print $1}'`<br />

# inum = inode (index node) number of file<br />

# Every file has an inode, a record that hold its physical address info.<br />

echo; echo −n "Are you absolutely sure you want to delete \"$1\" (y/n)? "<br />

# The '−v' option to 'rm' also asks this.<br />

read answer<br />

case "$answer" in<br />

[nN]) echo "Changed your mind, huh?"<br />

Chapter 12. External Filters, Programs and Commands 152

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

Saved successfully!

Ooh no, something went wrong!