0

I can read a file in zsh with $(< file); for example:

% print 'Hello, world!' > test
% x=$(< test); print $x
Hello, world!

However, errors are printed to stderr; for example:

% x=$(< doesnt-exist); print $x
zsh: no such file or directory: doesnt-exist

# The actual error in my script, for posterity.
% x=$(< /sys/class/hwmon/hwmon4/temp2_input); print $x
zsh: error when reading /sys/class/hwmon/hwmon4/temp2_input: no such device or address

Is there any way to capture or silence this error? You can test for readability or use cat 2>&1 and checking the exit code (which is what I used for now), but I wonder if $(< file) can be used too.

1 Answer 1

2

You can redirect in the normal way even when doing a variable assignment.

x=$(< doesnt-exist) 2>/dev/null ; print -r -- $x

That should be silent.

1
  • $(< doesnt-exist) 2>/dev/null) also seems to work; is there a difference? 🤔 Commented Mar 29, 2022 at 21:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .