Handling errors in shell scripts
Now and then users encounter unexpected errors in shell scripts. Common causes
are when files or networks are not available or executables crash because of
bugs or bad data. Also, shell scripts can be written with unanticipated
dependencies on the environment and can be more or less robust in their syntax
and error handling. As an example consider the following bourne/korn shell
# do not do this!
rm -rf *
There are two potential problems with this.
Fortunately for the user from which this example was taken, HPCCC staff were
able to recover the lost files from a backup. But remember, not all file
systems on HPCCC systems have backups.
- If the variable "subdir" is not defined, the cd sees no argument and the
directory is changed to the users HOME directory - then all files and
sub-directories are recursively removed (except dot files and directories).
- If the variable "subdir" is defined but does not specify a valid directory,
the cd will fail and the directory will not be changed - then all files etc.
in the current directory will be deleted.
Here are several strategies suggested by HPCCC staff to catch errors using
shell syntax. This will lessen the chance of such disasters happening.
- Probably the best solution in this case is to refer to the variable as
In this case the script will exit with an error message if subdir is not
- Use && or || to test the exit code (only good if $subdir is defined)
cd $subdir || exit 1 # will exit if cd $subdir fails
rm -rf * # or continue on
- Test for existence of $subdir first
test -n "$subdir" || exit 1
test -d "$subdir" && cd $subdir || exit 1
[ -d $subdir ] && cd $subdir || exit 1 # same as above for ksh
- You can also use if rather than && or || but that may be awkward if you
want to check many commands
if cd $subdir;
then rm -rf *
else exit 1
if test -n "$subdir"
if cd $subdir
rm -rf *
echo cd failed - bailing out
echo variable '$subdir' is not defined - bailing out
Last updated: 16 Mar, 2012
Email problems, suggestions, questions to
for the userguide structure.