How can I ignore errors with bash stdin redirection?

Viewed 426

I want to read a file into a variable. I can do this with a stdin redirection operator:

MYVAR=$(</some/file)

However, the file is a sysfs node and may error out. I'm also using set -o errtrace and want to ignore the error if it happens, just getting an empty variable. I've tried the following but surprisingly it always gives an empty variable.

MYVAR=$(</some/file || true)

Why is it always empty?

I could use cat:

MYVAR=$(cat /some/file 2>/dev/null || true)

but would like to know if it's possible without.

2 Answers

|| true should be outside the command substitution.

MYVAR=$(</some/file) || true

Your attempt failed because $(<file) is a special case, it doesn't work if there's anything else within the parantheses other than stdin redirection operator and the pathname.

The $(</file) syntax is a 'specific bash specialty'

If you change from that specific syntax, you just redirect into nothingness.

You either just use cat, or you wrap this specific syntax in a compound block:

{ MYVAR=$(</some/file); } 2>/dev/null
Related