In bash you can do:
echo test >&1(redirect to stdout, although it’s already going there)echo test >&2(redirect to stderr)echo test >&0(redirect to stdin)
When I do the last one my terminal still prints test as it would with the other two, but it’s hard to know why. So first off, why does this work at all? Secondly, are there any good uses for redirecting to stdin?
To be more precise, what
>&0does is duplicate file descriptor 0 as file descriptor 1. If the program’s stdin is only open for reading, then when your program tries to write to stdout (file descriptor 1), it will get an error because file descriptor 1 is also only open for reading.You can demonstrate this by writing a small shell script that inspects its own file descriptors:
10156115.sh:
And then invoke it with identifiable stdin, stdout and stderr:
The result is that you get the following in
stderr:However, by default, all three are a terminal: (output simplified)
Typically, all three are actually open read+write, so the
>&0redirect has no effect at all if used alone from a normal shell.Are there any uses for this?
There aren’t any common uses of this, but you might use it as a dirty hack to get a way to print to the terminal if whomever calls your script redirects
stdoutandstderr, and for whatever reason you’re not able to change that:But I wouldn’t recommend actually doing this.