Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash: Creating a second stderr alternative

I have a bash script that is intended to have an alternative second stderr analogue:

exec 3>/dev/tty
echo "STDOUT" >&1
echo "STDERR" >&2
echo "STDDEV" >&3

Thus I’d like to filter out each of it’s streams differently. It works correctly in the next cases:

  1. When I do not filter any stream.
$ bash test.bash 
STDOUT
STDERR
STDDEV
  1. When I suppress stdout
$ bash test.bash > /dev/null
STDERR
STDDEV
  1. When I suppress stderr
$ bash test.bash 2> /dev/null
STDOUT
STDDEV

Unfortunately, the attempt to suppress the stddev doesn’t results in actually suppressing it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ bash test.bash 3> /dev/null
STDOUT
STDERR
STDDEV

What am I doing wrong and how to fix it?
Thank you.

>Solution :

You could add a condition before creating FD3:

{ >&3; } 2>/dev/null || exec 3>/dev/tty

echo STDOUT >&1
echo STDERR >&2
echo STDDEV >&3

{ >&3; } evaluates to true when FD3 has been defined externally, like in test.bash 3> /dev/null

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading