How to read a file into a variable in shell?

In cross-platform, lowest-common-denominator sh you use:

value=`cat config.txt`
echo "$value"

In bash or zsh, to read a whole file into a variable without invoking cat:

echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker’s Wiki – Command substitution – Specialities.

Leave a Comment