Read file into variable while suppressing "No such file or directory" error

Viewed 1892

I want to read text file contents into a Bash variable, suppressing the error message if that file does not exist. In POSIX, I would do

var=$(cat file 2>/dev/null)

But I read (e.g. at How to read a file into a variable in shell) that it's a Useless Use of Cat in Bash. So, I'm trying those:

var=$(< file 2>/dev/null)
var=$(< file) 2>/dev/null

But it the first doesn't read an existing file, and both print -bash: file: No such file or directory if the file does not exist. Why doesn't this work? (Especially: What completely breaks the first one?)

What does work is this:

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

But it's ugly and cumbersome. So, is there a nicer syntax, or is this a valid use of cat after all?

4 Answers

Define a commands block with curly braces and redirect the stderr to /dev/null for the whole block.

{ IFS= read -rd '' var <file;} 2>/dev/null
Related