3

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.

oguz ismail
  • 1
  • 16
  • 47
  • 69
jozxyqk
  • 16,424
  • 12
  • 91
  • 180
  • What do you want to do if it errors out? What do you expect to store in the variable? – Inian Aug 07 '20 at 20:19
  • Just an empty variable. The node doesn't write anything to stdout if there is an error so that's what I'm hoping to capture. – jozxyqk Aug 07 '20 at 20:22

2 Answers2

2

|| 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.

oguz ismail
  • 1
  • 16
  • 47
  • 69
1

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
Hielke Walinga
  • 2,677
  • 1
  • 17
  • 30