Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between "exec" and "exit" in bash

Tags:

bash

exit

exec

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 :)

like image 746
Martin Avatar asked Dec 04 '22 05:12

Martin


1 Answers

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
like image 56
zwol Avatar answered Jan 01 '23 22:01

zwol