I want to read the contents of a text file in a Bash variable, suppressing the error message if this file does not exist. On POSIX, I would do
var=$(cat file 2>/dev/null)
But I read (for example, how to read a file in a variable in the shell ) that this is useless use of Cat in Bash. So I'm trying:
var=$(< file 2>/dev/null)
var=$(< file) 2>/dev/null
But he first does not read the existing file, and both print -bash: file: No such file or directoryif the file does not exist. Why is this not working? (Especially: what completely destroys the first?)
What kind of work is this:
{ var=$(< file); } 2>/dev/null
But it is ugly and bulky. So, is there a better syntax, or is it the actual use of cat in the end?