wonk0
wonk0

Reputation: 13952

How to tell if output was sent to stderr

I have to wrap a command in a bash script.

If the command exits with an exit code != 0 and/or writes to stderr a failure occurred which has to be handled.

The first condition is simple. But how to tell if there was output to stderr? I don't want to intercept or capture the output (unless there is no other way), I simply need to know if there was any.

Upvotes: 3

Views: 2232

Answers (2)

meuh
meuh

Reputation: 12255

You can do this by noting that a process's file descriptors are exposed in /proc/. For example if you do

$ ls -l /proc/self/fd/2
lrwx------ 1 meuh meuh 64 Jul 16 10:06 /proc/self/fd/2 -> /dev/pts/2

in an xterm or similar you can see that stderr for self, bash, is a pty. Follow the symlink in the ls to get the real time of last modification of the pty:

$ ls -lL /proc/self/fd/2
crw--w---- 1 meuh tty 136, 2 Jul 16 10:05 /proc/self/fd/2

A better command to use is stat which gives better time resolution.

$ stat -L -c %y /proc/self/fd/2
2015-07-16 10:03:54.553125813

So simply save the timestamp before your command, and compare it after the command to see if it is different.

before=$(stat -L -c %y /proc/self/fd/2)
if mycommand &&
 after=$(stat -L -c %y /proc/self/fd/2) &&
 [ "$after" = "$before" ]
then echo 'command ok'
else echo 'command fail'
fi

Upvotes: 1

pasaba por aqui
pasaba por aqui

Reputation: 3529

Suggestion: "tee" stderr to a temporary file and check if this file has non-zero size at command end.

Upvotes: 2

Related Questions