Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.