[Cialug] Having a "this should work" moment
Ken MacLeod
ken at bitsko.slc.ut.us
Fri Oct 2 11:19:33 CDT 2009
On Thu, Oct 1, 2009 at 8:58 PM, Josh More <morej at alliancetechnologies.net>wrote:
> You can reference them by their file descriptor (the number) or various
> variables depending on which standard libraries you wish to use. What
> Ken did here was redirect Standard Error (2) into Standard Out (1) using
> the Bash method of 2>&1. (Other shells may use other methods.)
>
> Thus, though it seems backwards, you have to remember that Bash parses
> the entire command line before it passes anything to the commands on it.
> By moving the 2>&1 to the end, Bash doesn't see it as an argument to
> the commands, but does the redirection AND THEN runs the commands. In
> effect,
>
Bash will also "parse out" redirects regardless of where they are in a
command. These are equivalent for example:
date >/dev/null 2>&1
>/dev/null 2>&1 date
It's the order that's important, though. Bash will parse the redirects in
order so these read as "redirect stdout (file descriptor 1) to /dev/null
then redirect stderr (file descriptor 2) to the same file as file descriptor
1."
In the later email, where the redirects were out of order ("2>&1 >smb.log"),
stderr was redirected to the same as file descriptor 1 which was still going
to the current terminal, then stdout was redirected to smb.log.
Just to complete the picture: There's a special case with pipes. Pipes
normally work with stdout, piping stdout of the command on the left into
stdin of the command on the right. The pipe file descriptors are set up
first before other redirects are applied. So the following reads "create a
pipe from stdout of command1 to stdin of command2, then redirect stderr of
command1 into the same file as file descriptor 1 of command1 (the pipe)":
command1 2>&1 | command2
make 2>&1 | less
-- Ken
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://cialug.org/pipermail/cialug/attachments/20091002/54a3985f/attachment.htm
More information about the Cialug
mailing list