Silent Bash Substitution – How to Make Bash Substitution Silent

bashcommand-substitutionstderr

I want to replace cat:

var=$(cat "filename" 2>/dev/null)

by bashism syntax:

var=$(<"filename")

The problem is that I don't know how to make the bashism silent to avoid such warnings:

bash: filename: No such file or directory

I've tried this:

var=$(2>/dev/null <"filename")

but it does not read existing files into var anymore.

Best Answer

Wrapping the assignment into a compound block and using a redirection on that seems to work:

{ var=$(<"$file"); } 2>/dev/null;

e.g.

$ echo hello > test1; rm -f test2
$ file=test1; { var=$(<"$file"); } 2>/dev/null; echo "${var:-[it is empty]}"
hello
$ file=test2; { var=$(<"$file"); } 2>/dev/null; echo "${var:-"[it is empty]"}"
[it is empty]

Just don't use ( .. ) to create a subshell, since then the assigned variable would be lost.

Related Question