I have seen both “exit” and “exec” used in bash script to stop script execution if an error has occurred. For example:
if [ ! -f file ]; then
echo "no file"
exit 1
fi
and:
if [ ! -f file ]; then
exec echo "no file"
fi
What is the best practise here and why? Wider discussion/explanations regarding “exec” and “exit” are welcome as well 🙂
exitjust exits the shell, returning the specified numeric exit code (or 0 if omitted) to the parent process. It is equivalent to the C library routine also calledexit, or to returning frommain.execreplaces the shell with a new executable image (still running in the same process), which will in due course exit and return some code or other to the parent process. It is roughly equivalent to the C library routineexecvp.Your first example is almost, but not quite, the correct way to stop a script if an error has occurred. It should read
The
>&2, which is missing from your example, causes the error message to go tostderr, where it belongs, instead ofstdout, where it does not belong.Your second example is wrong. In addition to the error message going to the wrong place,
exec echowill stop the script (because/bin/echowill do its thing and then exit) but it will return exit code 0 to the parent process. Exit code 0 means success. Programs running in the Unix environment must always make sure to return a nonzero exit code when they have failed.The proper use of
execis in shell scripts that do some set-up work and then invoke a long-lived program written in another language, and don’t have anything to do afterward, so there’s no point keeping the shell process hanging around. For example: