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: $(< file) reads a file into a shell variable without cat

Shell
~/tips/tip-shell-read-file-dollar-lt

version=$(< VERSION)

Load a small file into a variable without starting an extra cat process.

$(cat file) is the usual way to read a file into a variable. Bash has a shorter form that skips the cat process altogether.

Put just the input redirection inside the command substitution:

version=$(< VERSION)
echo "building $version"

The result is the same as with cat: the whole file, with trailing newlines removed. That last part is handy for files with one value, like a version number or a key, because you do not get a stray empty line at the end.

It saves a fork, which hardly matters for one call but adds up in a loop over hundreds of files. Mostly I like it because it reads as what it does.

Two things to know. It is a bash and zsh feature; in a plain sh such as dash, $(< file) gives you an empty string without an error. And when the file does not exist, bash prints an error and the variable ends up empty, so check with [ -r file ] first if the value matters:

[ -r VERSION ] || { echo "VERSION missing" >&2; exit 1; }
version=$(< VERSION)

Further reading: Bash manual: Command Substitution

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