Bash Exec Redirection
Exec redirection is a redirect applied to the whole script from one line onward. One exec line changes where every later command writes, with no redirect repeated on each command.
One line redirects the rest
A single exec line moves all later output to a file. Both echo lines land in the file with no redirect on either command.
exec 3>&1
exec > all.txt
echo "line one"
echo "line two"
exec 1>&3
exec 3>&-
cat all.txtErrors go to their own file
Exec moves the whole error stream to a file, while normal output still reaches the screen. The failed listing appears only when the file is read back.
exec 3>&2
exec 2> errors.txt
echo "screen line"
ls missing-file.txt
exec 2>&3
exec 3>&-
cat errors.txtAppend keeps earlier log lines
Exec with >> adds to the log instead of erasing it. The old line stays, and the new line joins it.
printf 'old line\n' > run.log
exec 3>&1
exec >> run.log
echo "new line"
exec 1>&3
exec 3>&-
cat run.logExample
exec 3>&1
exec 4>&2
exec > run.log 2>&1
echo "step one done"
echo "step two done"
ls missing-file.txt
exec 1>&3
exec 2>&4
exec 3>&-
exec 4>&-
echo "run finished"
echo "log:"
cat run.logKey points
- Whole-script scope: exec >file redirects all later output until the script ends or output is restored.
- Restore with a saved copy: save output first with exec 3>&1, then restore with exec 1>&3.
- Error stream too: exec 2>file captures error output from every later command.
- Append form: exec >>file adds to a log instead of erasing it.
- Combined form: exec >file 2>&1 sends both streams to one file.
- No command form: exec with only redirects changes the shell itself, while exec with a command replaces the shell.
- Honest limit: output redirected away is lost unless a saved copy restores it or the file is read back.
In this example, the script saves both standard streams, then redirects the whole script to one run log. Two steps write to the log, and a failed listing adds its error line to the same log. Both streams are restored before the script prints that the run finished and shows the log.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does `exec > log.txt` with no command do?