io

exec

Replaces the current shell process with COMMAND (no new process is created). Without a command, applies redirections permanently to the current shell — a common way to open long-lived file descriptors.

exec [-cl] [-a NAME] [COMMAND [ARGS]]   |   exec REDIRECTIONS

Common flags / operators

Flag / Operator Purpose
-l Pass command as a login shell (prepend - to argv[0])
-c Execute with an empty environment
-a NAME Use NAME as argv[0] of the new process
no-command form Applies redirections to the current shell

Examples

exec python3 app.py

Replaces the shell with python — no lingering shell process.

exec > logfile 2>&1

Redirects all subsequent stdout/stderr of this script to logfile.

exec 3< input.txt; read -r line <&3; exec 3<&-

Open fd 3, read from it, then close it.

exec 2>&1

Merge stderr into stdout for the rest of the script.

Gotcha

'exec CMD' does not return — anything after it in the script is unreachable unless exec fails. The redirection-only form persists for the WHOLE script; use { ...; } > file to scope redirection.

Related

← All Bash builtins · Linux commands