Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Clarification regarding I/O redirection

4 views
Skip to first unread message

Radoulov, Dimitre

unread,
Mar 9, 2011, 4:38:10 PM3/9/11
to

Hi all,
Advanced Bash-Scripting Guide, Chapter 20. I/O Redirection
(tldp.org/LDP/abs/html/io-redirection.html)

Could anyone kindly clarify the following comment:

"Close fd 3 for 'grep' (but not 'ls')":

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.


Why not for 'ls'?

Regards
Dimitre


Icarus Sparry

unread,
Mar 10, 2011, 1:43:18 AM3/10/11
to

The "3>&-" just to the left of the comment does close fd 3 for grep but
not ls. There is a second 3>&- just to the left of the pipe that closes
it for the shell that will turn into ls.

Short answer, as it is a different process.

The first thing that the shell notices in the second line is there is a
pipe. To handle this it calls fork() to create another process, and then
each side of the pipe is handled in a different shell. Each shell then
handles the redirection ("2>&1 >&3 3>&-" for one shell and "3>&-" for the
other shell), and then each shell runs the command.

(There are lots of things I have skipped over, for example is it the
parent or the child that becomes the left hand side of the pipeline, how
running the command might differ depending on if the command is a builtin
to the shell or not, if even the redirection is handled differently or
not if it is a builtin command)

Radoulov, Dimitre

unread,
Mar 10, 2011, 5:02:45 AM3/10/11
to


Icarus,
thank you for clarifying!

It was my wrong interpretation that fd 3 of the ls parent shell remains
open at that point (that the second 3>&- just to the left of the pipe
doesn't close fd 3 for ls).

Best regards
Dimitre

0 new messages