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 :)
exit
just 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 called exit
, or to returning from main
.
exec
replaces 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 routine execvp
.
Your first example is almost, but not quite, the correct way to stop a script if an error has occurred. It should read
if [ ! -f file ]; then
echo "no file" >&2
exit 1
fi
The >&2
, which is missing from your example, causes the error message to go to stderr
, where it belongs, instead of stdout
, where it does not belong.
Your second example is wrong. In addition to the error message going to the wrong place, exec echo
will stop the script (because /bin/echo
will 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 exec
is 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:
#! /bin/sh
PATH=/special/directory/for/foo:$PATH
export PATH
exec foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With