Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

How do you open custom file descriptors with `exec`, and why would you?

AdvancedConceptArguments, I/O, here-docs, process substitution and subshells
Answer
exec 3> /var/log/app/audit.log     # open fd 3 for writing
echo "deploy started by $SUDO_USER" >&3
exec 4< hosts.txt                  # open fd 4 for reading
while read -r h <&4; do ssh "$h" uptime; done
exec 3>&- 4<&-                     # close them
exec {lockfd}>/run/lock/job.lock   # Bash 4.1+: let Bash pick a free fd number
flock -n "$lockfd" || exit 0

Uses: a separate audit stream, reading a file while the loop body uses stdin, holding a flock lock, and BASH_XTRACEFD to send set -x output to its own file.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells