Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
Ankur Agarwal Avatar asked Nov 21 '10 22:11

Ankur Agarwal


2 Answers

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.

like image 151
jilles Avatar answered Sep 19 '22 13:09

jilles


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.

like image 30
SiegeX Avatar answered Sep 17 '22 13:09

SiegeX