brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: exec 3> keeps a file open for the rest of a shell script

Shell
~/tips/tip-shell-exec-file-descriptor

exec 3>>report.log

Open a log file once and write to it many times through a number.

When a loop writes to the same file on every round, each >> opens and closes it again. You can also open it once and give it a number.

File descriptors 0, 1 and 2 are stdin, stdout and stderr. Numbers 3 to 9 are free for your own use:

exec 3>>report.log
for host in web db cache; do
  echo "checked $host" >&3
done
exec 3>&-

The first line opens report.log for appending and keeps it open as descriptor 3. Each >&3 writes to it, and 3>&- closes it at the end. Normal output still goes to the screen, so you can keep the progress messages and the report apart.

I find it reads better than a long string of >> report.log on every line, and the filename lives in one place.

Watch the direction: exec 3> with one > empties the file when it opens, 3>> appends. Also keep the numbers low; bash uses some higher descriptors itself, and if you want a free number picked for you, bash can do that with exec {fd}>>report.log and then >&$fd.

Further reading: Bash manual: Redirections

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link