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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With