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.
More on Arguments, I/O, here-docs, process substitution and subshells
How does `getopts` work? Show a complete example.IntermediateWhat is the difference between `getopts` and `getopt`?AdvancedExplain file descriptors 0, 1 and 2 and the main redirection operators.BeginnerWhy is `cmd 2>&1 > file` different from `cmd > file 2>&1`?AdvancedWhat is a here-document, and what is the difference between `<<EOF`, `<<'EOF'` and `<<-EOF`?BeginnerWhat is a here-string (`<<<`)?Intermediate