How to capture output from certain Unix commands

May 01, '08 07:30:00AM

Contributed by: robg

I was recently trying to do some simple shell scripting with the command httpd -t, which runs a syntax check on the Apache configuration files. If everything is OK, it returns Syntax OK, otherwise, it will try to tell you what's wrong with the files. I wanted to grab the output of the syntax check and display it in my script, but wasn't having any luck -- any attempt to redirect the output, or assign it to a variable, resulted in nothing (empty variable, empty file, etc.). Unix wizards can stop reading this hint now, for I'm sure you know what the problem is...

After much Googling, I discovered that some Unix commands create their output by writing to standard error (STDERR) instead of standard output (the Terminal window, typically). As a result, operations that capture standard output won't work for these types of messages, even though the message itself is displayed in the Terminal window. I found the solution in the Wikipedia entry for stderr: append 2>&1 to the end of the command (note that this is for sh-style shells, including bash, the OS X default shell). This redirects standard error to the same destination as standard output, meaning the data can then be captured as you wish. To put the output of httpd -t onto the clipboard, for instance, you could use this:

$ httpd -t 2>&1 | pbcopy
$ pbpaste
Syntax OK
Or if you wished to assign the output to a variable for use in a script:
CONFIGTEST=`httpd -t 2>&1`
I'm sure there are a number of other commands that output via standard error -- one for certain is ssh -V, which returns the version information for ssh.

Comments (13)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20080501060739120