bash exec - ghdrako/doc_snipets GitHub Wiki

The exec command in Bash is used to replace the current shell process with a new process. Instead of starting a new process and keeping the old one running, exec replaces the shell entirely. This can be useful for optimizing resources or when you want to switch to another program in your script without returning to the original script.

#!/bin/bash
# Before exec, normal Bash script
echo "This message is before exec"
# Replace the current shell with the 'ls' command
exec ls
# This message will never be executed because exec replaces the shell
echo "This message will never be printed!"

When exec is used, it replaces the current shell process with the specified command, so the shell script stops executing, and the new process takes over.

Use cases: exec is useful when you want to optimize system resources because no extra process is created. For example, if you're running a long-lived service (like a web server), you might use exec to switch to the service process instead of keeping the Bash script in memory.Why no return to script: Once the new process is started, the original script is completely replaced, so any commands after exec are not run.

exec can also be used to redirect file descriptors, like exec > logfile.txt, which redirects standard output to a file.If no command is provided after exec, it can be used to redirect or manipulate input/output without replacing the current process.