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?
With BASH it is easy to test if file exists before reading it in
[ -e file ] && var=$(< file )
As Inian points in the comments the file might exist but the user might not have sufficient rights for reading it. The -r
test would take care of that.
[ -r file ] && var=$(< file )
var=$(cat file 2>/dev/null)
This is a Useful Use of Cat. It enforces an order of operations: stderr is redirected before file
is opened. It serves a purpose. Don't feel bad about using it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With