Help me understand this simple io redirection in bash from the ABS manual
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 third line where fd 3 closes.
Doubts: The first line redirects fd 3 to stdout, globally ... right?
Questions: What happens on the 2nd line? Please provide a detailed explanation if possible.
This is probably the best redirection tutorial I've found. Whenever I see some kind of funky redirection, I talk about it to help me with this.
Redirects are handled by an external command into the internal command and inside the command from left to right. Therefore, ls -l 2>&1 >&3 3>&- initially gets stdout into the pipe. Then stderr is redirected to the pipe, stdout becomes the original stdout (unpiped), and the extra fd is closed. Thus, the regular output ls -l remains unchanged, error output lines containing "bad" are sent to stdout, and the rest of the error output is discarded.