Robins blogg

2008-02-23

Bash fd abuse

Filed under: — site admin @ 12:02

A fun bash feature is redicecting to extra file descriptor. It allows you to filter
stout and stderr separately like this.

(some-command | stdout-filter >&3) 2>&1 | stderr-filter) 3>&1

The first part “some-command | stdout-filter” does stdout filtering. Then “>&3″ send that to another pipe, fd#3.
Meanwhile “2>&1″ now directs stderr from some-command to stdout (fd#1) and “| stderr-filter” does the filtering.
Finally 3>&1 directs 3 to stdout of the process that started the whole command, combining the outputs.

Example:

$ ((ls -l x y README | sed 's/^/STDOUT/' >&3) 2>&1|sed 's/^/STDERR/' ) 3>&1
STDERRls: cannot access x: No such file or directory
STDERRls: cannot access y: No such file or directory
STDOUT-rw-r--r-- 1 me me 8443 Feb 17 00:26 README

Powered by WordPress