Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm writing a bash script that should exit the error code of the last failed command and not continue execution. This can be achieved by adding a || exit $? everywhere, but is there an easier way, e.g. a set option at the start to do this without uglifying every line?

share|improve this question
1  
A side not is that exit $? is not needed. By default, your script will exit with the $? of the last command. exit $? and exit are equivalent in bash. –  jordanm Oct 17 '12 at 17:55
    
@jordanm You mean the $? was superfluous? The exit itself (without set -e as I learned) was necessary. But thanks, good to know for situations where I don't want to abort on all errors. –  Tobias Kienzler Oct 17 '12 at 17:58
1  
Yes, I could have been more clear. The $? is superfluous. –  jordanm Oct 17 '12 at 19:25
add comment

2 Answers

up vote 9 down vote accepted

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. 

...

share|improve this answer
2  
Instead of the dummy padding you could quote the documentation. –  manatwork Oct 17 '12 at 10:09
    
there you go :) –  Chris Card Oct 17 '12 at 10:39
1  
Note that non-zero return codes only cause a set -e script to fail when the return codes aren't tested. The exact meaning of tested isn't easy to specify, but the basic idea is that failingcmd || nonfailing won't make the whole script fail. –  dubiousjim Oct 17 '12 at 18:25
    
Make sure to read about the pitfalls. –  l0b0 Oct 18 '12 at 9:44
add comment

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

share|improve this answer
1  
Hey thanks, and welcome to unix.stackexchange! As jordanm mentioned it turns out exit alone will behave the same way as exit $? does –  Tobias Kienzler Oct 18 '12 at 5:35
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.