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?