3

This is probably the best place to ask the question in its simplest form. I am writing a script which takes output of a command and puts it into a variable. After some debugging I figured out the command when it errors does not goto stdout but to the console (or wall). See example below:

When the command runs successfully

root@local# apcaccess status
APC : 700
VERSION : xxxxx
BATTSTAT : AC

When the command errors out

root@local# apcaccess status
apcupsd @ localhost: Connection Refused.

root@local# apcaccess status | grep -i version
apcupsd @ localhost: Connection Refused.

I have noticed when I try to pipe the command through grep 'apcaccess status | grep -i version' I will get the version number on a successful run but on the system that it errors out on I get the error message. I believe it is not going through stdout.

The question is: how can I force the output to goto stdout?

2 Answers 2

6
# apcaccess status 2>&1 | grep -i version

This will redirect stderr to stdout, so grep will see the output.

1
  • You'll find this trick useful elsewhere too. For example some --help entries go to stderr instead of stdout, forcing you to: foobar --help 2>&1 | less
    – Twirrim
    Jul 7, 2011 at 23:36
2

The reason is there are actually two file descriptors open which "print" to your screen. stdout (represented by file descriptor 1) and stderr (file descriptor 2). When you pipe one command to another you simply take the stdout from the first command and "pipe" it as the stdin to the second command. But if the first command printed something to stderr (usually an error message) than it is not passed through the pipe but printed directly to your screen.

So you need to redirect stderr to stdout. Achieved by the following.

command1 2>&1 | command2

Protips: The reason the ampersand is necessary is because you need to say that you are redirecting stderr (2) into the file descriptor stdout (1). Otherwise without the ampersand you are simply telling stderr to redirect to the file named '1' in the current working directory. Similar to what you might do when you dump the "output" of a command (stdout) to a file via 'command > myfile.log'. Putting no file descriptor in front of the redirection command defaults to 1 (stdout).

You must log in to answer this question.

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