UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 46.7 Quoting and Command-Line Parameters Chapter 46
Shell Script Debugging and Gotchas
Next: 46.9 If Command Doesn't Return a Status, Test the Error Messages
 

46.8 Test Built-In Commands for Failure

Some old-timers in shell programming (myself included) tend to depend on shell "features" that they shouldn't. Here's one bad assumption: the Bourne shell will exit if the cd command fails. That wasn't documented (as far as I know), but, even so, people wrote scripts like this:

...
cd $somedir
rm -rf *

The Korn shell didn't have that undocumented behavior. If a cd failed, ksh would print an error message and keep on reading the script. That caused some infamous problems when Bourne shell users gave their scripts to the Korn shell!

Unless the behavior of a command is documented, don't count on it to keep a disaster from happening. In the preceding script, for example, the rm command removed everything from a directory different than $somedir. One thing that's worth doing: test the exit status of a built-in and quit if it returns non-zero status. For instance, the || operator (44.9) makes this script abort if the cd fails:

...
cd $somedir || exit
rm -rf *

Careful testing of scripts that could do something disastrous - trying to find places where they'll fail - can be worth the time. That's especially true when you run the script on a new system or with another shell: test the built-in commands' exit status after they fail.

- JP


Previous: 46.7 Quoting and Command-Line Parameters UNIX Power ToolsNext: 46.9 If Command Doesn't Return a Status, Test the Error Messages
46.7 Quoting and Command-Line Parameters Book Index46.9 If Command Doesn't Return a Status, Test the Error Messages

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System