Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting errors *from redirection operations themselves*

Let us say I have some file called a.txt in the current directory. It's chmod value is 000.

Therefore, if I try to write to it, I get the following output:

> printf "Hello" >> a.txt
-bash: a.txt: Permission denied

How can I suppress this output? I have tried appending 2>/dev/null to my command, but this redirection does not seem to work as I had originally hoped.

like image 273
Bob Jones Avatar asked Mar 02 '23 07:03

Bob Jones


1 Answers

The answer by that other guy is correct if you also want to suppress errors from the command you're running, not just from the redirections performed before starting it.

If you want to only suppress messages from the redirection itself and not also suppress error messages from actual execution, then you need an extra pair of redirections, to temporarily store the original value of stderr so you can later restore it:

printf "Hello" 3>&2 2>/dev/null >>a.txt 2>&3 3>&-

This breaks down as follows:

  • 3>&2 copies the original stderr (FD 2) to a file descriptor that is unused by default (FD 3), creating a backup of the original destination.
  • 2>/dev/null then points stderr to /dev/null.
  • >>a.txt points stdout (FD 1) to aa.txt, with stderr pointing to /dev/null.
  • 2>&3 copies our backup on FD 3 back to FD 2, restoring stderr to its original destination so the program being run can log errors.
  • 3>&- deletes the backup, leaving the file descriptor table as it would have been if we'd done nothing at all. (It's generally safe to leave this out -- most well-behaved programs will simply ignore nonstandard file descriptors' initial values unless explicitly told to do otherwise).
like image 177
Charles Duffy Avatar answered Mar 05 '23 15:03

Charles Duffy