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
source (.)
Executes FILE in the CURRENT shell (no subshell), so variables, functions, and aliases defined in it persist. Contrast with 'bash file' which runs in a child process — its side effects vanish when it exits.
trap
Registers a command to run when the shell receives a signal or special event (EXIT, ERR, DEBUG, RETURN). The workhorse for cleanup handlers, temp-file removal, and error diagnostics in scripts.
echo
Writes arguments to stdout separated by spaces and terminated with a newline. Behavior across systems is inconsistent (especially escape processing) — prefer printf for anything with formatting or portability requirements.
printf
Formats and prints arguments according to a C-style format string. Portable, precise, and reuses the format string if extra arguments are provided — the preferred replacement for echo when you need formatting.
read
Reads a single line from stdin (or a file descriptor) and splits it into the given variables using IFS. The workhorse for line-by-line input processing and interactive prompts.