I have seen wrapper script examples which in a nutshell are following:


echo "This is the wrapper script, it will exec "$myprog""

exec "$myprog" "$@"

As seen above, they use exec to replace the newly created shell almost immediately with the $myprog. One could achieve the same without exec:


echo "This is the wrapper script, it will exec "$myprog""

"$myprog" "$@"

In this last example, a new bash instance is started and then $myprog is started as a child process of the bash instance.

What are the benefits of the first approach?


2 Answers 2


Using exec makes the wrapper more transparent, i.e. it makes it less likely that the user or application that calls the script needs to be aware that it's a relay that in turns launches the “real” program.

In particular, if the caller wants to kill the program, they'll just kill the process they just launched. If the wrapper script runs a child process, the caller would need to know that they should find out the child of the wrapper and kill that instead. The wrapper script could set a trap to relay some signals, but that wouldn't work with SIGSTOP or SIGKILL which can't be caught.

Calling exec also saves a bit of memory (and other resources such as PIDs etc.) since it there's no need to keep an extra shell around with nothing left to do.

If there are multiple wrappers, the problems add up (difficulty in finding the right process to kill, memory overhead, etc.).

Some shells (e.g. the Korn shell) automatically detect when a command is the last one and there's no active trap and put an implicit exec, but not all do (e.g. not bash).

  • Bash execs if there is only one command (and no traps). AFAIK this isn't documented. Feb 12, 2022 at 7:40
  • @PaulDraper: can you somehow confirm this? A quote from source code perhaps? This would be huge!
    – MestreLion
    Mar 4, 2023 at 19:38
  • 1
    @MestreLion you can confirm this by running `bash -c 'echo $$; sleep infinity'. Then inspect that pid and you'll see that it is now the sleep process. Mar 12, 2023 at 20:32
  • yes, bash does this. the behavior is gated by the ONESHOT define, which appeared in bash 2.0. this is the relevant code, the comment explains the necessary conditions for the implicit exec to happen. the actual code implementing these conditions is here. Aug 15, 2023 at 0:39

Finding no duplicates... refer to the FreeBSD handbook, which gives a good enough reason:

The exec statement replaces the shell process with the specified program. If exec is omitted, the shell process remains in memory while the program is executing, and needlessly consumes system resources.

which is essentially the reason explained to me quite a while back (by one of the porters), and is fairly well-known.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .