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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 30−3. test24, another buggy script<br />

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

#!/bin/bash<br />

# This is supposed to delete all filenames in current directory<br />

#+ containing embedded spaces.<br />

# It doesn't work. Why not?<br />

badname=`ls | grep ' '`<br />

# echo "$badname"<br />

rm "$badname"<br />

exit 0<br />

Try to find out what's wrong with Example 30−3 by uncommenting the echo "$badname" line. Echo<br />

statements are useful for seeing whether what you expect is actually what you get.<br />

In this particular case, rm "$badname" will not give the desired results because $badname should not be<br />

quoted. Placing it in quotes ensures that rm has only one argument (it will match only one filename). A partial<br />

fix is to remove to quotes from $badname and to reset $IFS to contain only a newline, IFS=$'\n'.<br />

However, there are simpler ways of going about it.<br />

# Correct methods of deleting filenames containing spaces.<br />

rm *\ *<br />

rm *" "*<br />

rm *' '*<br />

# Thank you. S.C.<br />

Summarizing the symptoms of a buggy script,<br />

1. It bombs with a "syntax error" message, or<br />

2. It runs, but does not work as expected (logic error).<br />

3. It runs, works as expected, but has nasty side effects (logic bomb).<br />

Tools for debugging non−working scripts include<br />

1. echo statements at critical points in the script to trace the variables, and otherwise give a snapshot of<br />

what is going on.<br />

2. using the tee filter to check processes or data flows at critical points.<br />

3. setting option flags −n −v −x<br />

sh −n scriptname checks for syntax errors without actually running the script. This is the<br />

equivalent of inserting set −n or set −o noexec into the script. Note that certain types of<br />

syntax errors can slip past this check.<br />

sh −v scriptname echoes each command before executing it. This is the equivalent of inserting<br />

set −v or set −o verbose in the script.<br />

The −n and −v flags work well together. sh −nv scriptname gives a verbose syntax check.<br />

Chapter 30. Debugging 320

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

Saved successfully!

Ooh no, something went wrong!