Shell – Does running “exec echo some; echo test” in bash never print “some test”

execshell

Does running exec echo "some "; echo "test" in bash never print "some test"?

I would seek confirmation to this question, as I am writing a small shell script and I would like it to not contiue anything after the exec command has been called.

I think that I would not need to worry, as my understanding, after consulting:

  • man 3 exec
  • man 1p exec

The shell scripts, when executed by the shell will make

  1. the shell execute the program exec, which
  2. uses the exec*** family system calls that replace the shell/bash that which has been executing the script, by this impeding further actions of the shell (which was "replaced")

As laid out before, main goal of this question is to seek confirmation for my reasoning as to prevent that anything in the script occuring after the exec (such as echo test) would be executed.

I would appreciate a general answer (POSIX), as far as possible, but just in case of particularities I am most interested in GNU/Linux and GNU/Bash

Best Answer

exec does always finish the script if it executes a command and does so successfully (not related to the command's exit code but to starting it).

exec can be run without a command in a very useful way: To permanently redirect file descriptors:

exec 3>/path/to/file

If the command cannot be started then the shell behaviour depends on the configuration. bash exits by default.

It may be best for you to use a function instead:

safe_exec () {
    cmd="$1"
    if test -z "$cmd" || ! test -f "$cmd" || ! test -x "$cmd"; then
        exit 1
    else
        exec "$@"
    fi
}

safe_exec echo "some "; echo "test"
Related Question