How to write an abort-on-error script without adding `|| exit $?` to every line?

set -e ?

set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
Set or unset values of shell options and positional parameters.

Change the value of shell attributes and positional parameters, or
display the names and values of shell variables.

 Options:
   -a  Mark variables which are modified or created for export.
   -b  Notify of job termination immediately.
   -e  Exit immediately if a command exits with a non-zero status. 
...

You might join all the commands with && and use || exit $? at the very end of the block. For example:

#!/usr/bin/ksh
ls ~/folder &&
cp -Rp ~/folder ~/new_folder &&
rm ~/folder/file03.txt &&
echo "This will be skipped..." ||
exit $?

if there is no ~/folder/file03.txt file, the last echo command will be skipped. You should receive something like this:

$ ./script.ksh
file01.txt  file02.txt
rm: cannot remove /export/home/kkorzeni/folder/file03.txt: No such file or directory
$ echo $?
1

Best regards, Krzysztof


You can define a trap function to capture any error that is occurring in the script.

#!/usr/bin/ksh
trap errtrap

function errtrap {
    es=$?
    echo "`date` The script failed with exit status $es " | $log
}

rest of the script follows.

The TRAP will capture any error at any command and will call the errtrap function. For better usage you can make the errtrap function generic and call that in any script that you are creating.

Tags:

Exit

Bash