This question already has an answer here:

I read content of the file into variable like this


But if the file doesn't exist I get accordingly an error message

bash: somefile: No such file or directory

Is it possible to redirect stderr to >/dev/null without using cat command?

marked as duplicate by Jeff Schaller, Community Mar 14 '18 at 10:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


In this case, either use cat:

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

or test for file existence first:

if [ -f somefile ]; then

To avoid the race condition in the last example (the file might theoretically disappear between the test and reading it):

if cp somefile myname 2>/dev/null; then
    rm -f myname

The following will not work:

var=$(<somefile) 2>/dev/null
var=$(<somefile 2>/dev/null)
  • This is the pettiest gripe, but the second fix has a race condition... – Michael Homer Mar 14 '18 at 9:04
  • @MichaelHomer It has. The file might theoretically disappear between the test and reading it. Another way would be to copy the file and read it if that succeeded, but the cat is probably best (and also portable). – Kusalananda Mar 14 '18 at 9:25

You can use:

{ var=$(<somefile); } 2> /dev/null
  • Hmm... yes, that would be best. Didn't we have this in an answer the other day (I can't find it)? – Kusalananda Mar 14 '18 at 10:28
  • @Kusalananda, yes, I couldn't find it either, but I'm pretty sure there's a recent dup too. – Stéphane Chazelas Mar 14 '18 at 10:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.