Ankur Agarwal
Ankur Agarwal

Reputation: 24758

Help me understand this simple io redirection in bash from ABS guide

exec 3>&1                           # Save current "value" of stdout.  
ls -l 2>&1 >&3 3>&- | grep bad 3>&- # Close fd 3 for 'grep' (but not 'ls').  
#              ^^^^   ^^^^
exec 3>&-                           # Now close it for the remainder of the script.  

I get the 3rd line where fd 3 is being closed.

Doubts: 1st line redirects fd 3 to stdout, globally... right?
Questions: What's happening on the 2nd line? Please provide a verbose explanation if possible.

Upvotes: 7

Views: 242

Answers (2)

SiegeX
SiegeX

Reputation: 140327

This is probably the best Redirection Tutorial I've found. Whenever I see some funky redirection going on, I refer to this to help me through it.

Upvotes: 2

jilles
jilles

Reputation: 11232

Redirections are processed outer command to inner command, and within a command from left to right. Therefore, ls -l 2>&1 >&3 3>&- initially gets stdout to the pipe. Then, stderr is redirected to the pipe, stdout becomes the original stdout (unpiped) and the extra fd is closed. So the regular output of ls -l remains unchanged, the lines of the error output that contain "bad" are sent to stdout and the rest of the error output is discarded.

Upvotes: 3

Related Questions