exec and time
With a command operand, successful exec program args replaces the current process image instead of returning to the calling script. The PID remains the same across successful process replacement; program arguments and environment determine the new program behavior. With no command, exec applies redirections to the shell (Chapter 12). Use a short-lived child shell for replacement practice. On failure, a noninteractive shell normally exits unless the execfail shopt option is enabled; never depend on code after exec running on success. Bash time is a reserved word that measures a pipeline, including builtins and groups. It normally reports elapsed, user and system time on stderr. TIMEFORMAT controls Bash timing text; %R, %U, %S represent elapsed, user and system seconds. time -p selects a portable-format report. An external time executable is a distinct interface. Timing varies by machine and load, so compare repeated measurements rather than asserting exact durations. If replacement fails with execfail enabled, the next command can inspect the failure status. A missing executable and a nonexecutable file are different failure cases. Timing output is not the measured command’s stdout, and its status still reflects the measured pipeline.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Replace a disposable child
bash -c 'printf "before\n"; exec bash -c "exit 6"; printf "unreachable\n"'printf 'status=%s\n' "$?"Expected stdout:
beforestatus=6The replacement exits with status 6; the old child code never resumes.
Check process identity across exec
( exec bash -c '[[ $BASHPID == $1 ]] && printf "same PID\n"' _ "$BASHPID" )Expected stdout:
same PIDThe child passes its PID as an argument and the replacement compares it.
Time a group with stable text
TIMEFORMAT='measurement complete'time { printf 'payload\n'; }printf 'status=%s\n' "$?"Expected stdout:
payloadstatus=0Expected stderr:
measurement completeThe literal format makes the fixture deterministic; use TIMEFORMAT="%3R seconds" to see a real measured duration.
Common mistakes
Never test exec replacement directly in a shell session you need to keep. Do not confuse elapsed time with CPU time, or stderr timing text with a failure.
Practice
Use a child Bash to print a message, exec another Bash that exits 6, and capture the resulting status in the parent. Time a fixed printf group and distinguish output from timing.
Next: Pipelines and PIPESTATUS