How can I suppress the following error

if true </dev/tty 2>/dev/null; then
   read -r "$VARIABLE" </dev/tty

seems not to ignore the error can't open /dev/tty: No such device or address. which was the purpose of the whole if clause. The error happens on the if ...

  • @Archemar, if /dev/tty cannot be opened for reading then true < /dev/tty will return a non-zero exit status and true will not be run. tty reports the name of tty device open on stdin if any. true < /dev/tty would check whether the process has a controlling terminal and that terminal device can be open for reading. – Stéphane Chazelas Jun 8 '20 at 15:11
  • yes, I check after posting comment (hence deletion). I use tty -s in similar situation. – Archemar Jun 8 '20 at 15:18
  • 1
    @Archemar, if it's to check whether stdin is a tty, [ -t 0 ] should be enough. – Stéphane Chazelas Jun 8 '20 at 15:22

Redirect stderr first:

if true  2>/dev/null </dev/tty; then
   IFS= read -r "$VARIABLE" </dev/tty

With zsh, you'd need:

if { true </dev/tty; } 2> /dev/null; then
   IFS= read -r "$VARIABLE" </dev/tty

as upon redirection failures, zsh restores the fds before outputting the error messages (which kind of makes sense to me, but that means the behaviour is inconsistent as that restoring doesn't happen when redirecting an external command).

That's assuming you want to read a line from the controlling tty device of the process if there's one.

But that's not much different from

IFS= read -r "$VARIABLE" 2> /dev/null </dev/tty

If /dev/tty cannot be open, the command (here read) is not run.

You could also do it like:

{ IFS= read -r "$VARIABLE" < /dev/tty 2>&3 3>&-; } 3>&2 2> /dev/null

For stderr to be redirected to /dev/null before /dev/tty is opened, and restored afterwards for read (for read to still be able to report read errors if any).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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