Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ignore errors with bash stdin redirection?

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.

like image 659
jozxyqk Avatar asked Dec 06 '25 14:12

jozxyqk


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.

like image 173
oguz ismail Avatar answered Dec 08 '25 07:12

oguz ismail


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
like image 28
Hielke Walinga Avatar answered Dec 08 '25 06:12

Hielke Walinga