Reading a file in a variable while suppressing the error "There is no such file or directory"

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?

+6
3

. cat , stderr, .

, , , THAT , , . " " , , .

if, , cat.

+1

BASH ,

[ -e file ] && var=$(< file )

Inian , , . -r .

[ -r file ] && var=$(< file )
+3
var=$(cat file 2>/dev/null)

This is a useful use of Cat. It performs an order of operations: stderr is redirected to open file. It serves a purpose. Do not feel bad to use.

+3
source

All Articles