Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 6 down vote accepted
# apcaccess status 2>&1 | grep -i version

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

share|improve this answer
    
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 '11 at 23:36
    
That did the trick, thanks! –  jinanwow Jul 7 '11 at 23:47

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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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