I'm a bit confused as to why when I'm redirecting the standard output of an echo command to the standard error, why I still get the argument printed in the terminal?
Here's is the line I ran
echo "potato" >&2
Could someone explain this to me? How does this command output anything, if the output was redirected somewhere else?
Thank you :)
I think what you want is:
From the
man
page for bash:Because standard error is also displayed in terminal by default. So you redirect your standard output to standard error which in turn gets redirected to the console. The result does not change.
Well, by default, your terminal shows both STDOUT and STDERR.
So, what you are seeing is STDERR.
If you want to hide STDERR:
echo "potato" 2>/dev/null >&2
/dev/null
is a black-hole, where you can redirect stuff you have no wish to see :)The output is simply going where it's told to go
By default file descriptor 1 and 2 point to the same location (note
>&2
is equivalent to1>&2
)And now let's say we redirect one of those file descriptors to point elsewhere
Note the output of
ls -l /proc/$$/fd/
went to filefoo
in our working directory rather than being printed to stdout.At first, when your terminal and shell starts, both STDOUT and STDERR points to the terminal output. Your command
echo "potato" >&2
is asking to redirect STDOUT to what STDERR points to. Thus this command has no effect at all.Here's some references:
> somefile
or1> somefile
redirects file descriptor 1 to the file named 'somefile', i.e. pointing STDOUT to 'somefile'n> somefile
redirects file descriptor n to the file named 'somefile', wheren
= 1, 2, 3, ...n
by default is 1, whenn
is omitted.n>&m
redirects file descriptor n to file descriptor m.n>&-
closes file descriptor n, where n = 1, 2, 3, ...command1 > /dev/null | comamnd2
first create pipe between command1, and command2, i.e. link STDOUT of command 1 to STDIN of command2. Then, STDOUT of command1 is redirected to /dev/null. This essentially cancels the pipe (disengages the pipe). Thus command2 will sees end of the STDIN input, i.e. STDIN of command2 is closed.So, it explains why the following command exchanges STDIN and STDOUT:
wc
points to pipe-inThe net effects are: FD1 now points to the terminal output. FD2 now points to the pipe-out, piping outputs to
wc
command.Hope this helps.