exec
Replace current process with a new program
TLDR
Execute a specific command using the current environment variables
SYNOPSIS
exec [-a name] [-c] [-l] [-m] [command [arguments...]] [redirections]
PARAMETERS
-a name
Sets the argv[0] name for the executed command as seen in ps(1).
-c
Executes command with an empty environment, except for exported shell variables.
-l
Invokes command as a login shell.
-m
Ignored option for POSIX compatibility.
DESCRIPTION
The exec command is a powerful shell builtin in Linux, primarily used to replace the current shell process with a specified command without creating a child process. This means the process ID (PID) of the shell remains the same, but it now runs the new executable. It's especially useful in shell scripts as the final step to launch the main program after setup, avoiding unnecessary process overhead.
When exec is called with a command and arguments, the shell overlays its image with the new program and terminates immediately upon success. If the exec fails (e.g., command not found), the shell continues execution.
Without a command, exec applies any redirections to the current shell's file descriptors permanently, allowing scripts to redirect all subsequent I/O without spawning processes. For example, exec > /var/log/script.log 2>&1 redirects stdout and stderr for the rest of the script.
Options control aspects like the environment, login shell behavior, and argv[0]. It's available in POSIX-compliant shells like Bash, Dash, and Zsh, making it portable across Unix-like systems. Common in init scripts, daemons, and login shells for seamless transitions.
CAVEATS
Replaces current shell process on success; shell does not return.
Fails silently if command not found, continuing script.
Redirections without command are permanent for the shell.
Not suitable for subshells, as effects don't propagate to parent.
EXAMPLES
exec /bin/ls -l — Replace shell with ls.
exec >outfile.log 2>&1 — Permanent output redirection.
exec -l /bin/bash — Restart as login shell.
exec -a mysh $SHELL — Relaunch shell with custom name.
EXIT STATUS
If command supplied, shell exits with its status (success or failure).
Without command, returns 0 after applying redirections.
HISTORY
Originated in the Bourne shell (sh, 1977). Standardized in POSIX.1-1992 as a required shell builtin. Bash (1989+) added options like -a and -c for enhanced control. Evolved for efficiency in process replacement, core to Unix scripting traditions.


