Capture output of certain Unix commands

Today’s hint will probably only appeal to those of you learning to use the Unix side of OS X. A while back, I was trying to capture the ouput of the Unix command httpd -t (which runs a syntax check on the Apache web server’s configuration files) to the clipboard. Typically, you do this in OS X by sending the command’s output through the pbcopy (pasteboard copy) command:

httpd -t | pbcopy

That should, in theory, put the output of the command on the clipboard. But in this case, it wasn’t working. After much investigation, what I learned is that some Unix commands, httpd -t included, don’t send their output to the Terminal in the usual way. The usual way in Unix is to send output to something called the “standard output,” which for all intents in this dicussion, means the Terminal window.

Instead, certain commands send their output to standard error (STDERR, in Unix parlance). Although this text is also displayed in Terminal, you can’t do anything with the output as you can if it were sent to standard output. (Unix wizards, please feel free to correct any of my mistakes in the above; it’s meant to be a summary view of the situation.)

The solution is to reroute what gets sent to standard error to standard output, using this syntax:

httpd -t 2>&1

The 2 represents standard error, and the 1 represents standard output. The bit in the middle, >& is the usual Unix redirect command (the greater than sign), followed by the ampersand, which changes the redirect’s output from a file (which is typical) to a file descriptor (in this case, the standard output).

I know that’s a mouthful, and I’ll admit that I don’t fully understand it—but I know it works, at least in the bash shell that’s been the default for a while now. Once the output is in standard output, it can just be fed through pbcopy as usual:

httpd -t 2>&1 | pbcopy

The end result, assuming there’s nothing wrong with your Apache configuration files, will be the text Syntax OK on your clipboard. I know that ssh -v (verbose mode ssh) also sends its output to standard error, as does time, and I’m sure there are many more.

If you’re a Unix expert and can clarify or expand on this in the comments, please feel free!

Shop Tech Products at Amazon