are there uses for '>&0' (redirect to stdin)?

bash, unix

Solution

To be more precise, what `>&0` does 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:

#!/bin/bash
bash -c 'ls -l /proc/$$/fd' >&0

And then invoke it with identifiable stdin, stdout and stderr:

$ touch stdin
$ ./10156115.sh < stdin > stdout 2> stderr

The result is that you get the following in `stderr`:

ls: write error: Bad file descriptor

However, by default, all three are a terminal: (output simplified)

$ ls -l /proc/$$/fd
lrwx------ 0 -> /dev/pts/14
lrwx------ 1 -> /dev/pts/14
lrwx------ 2 -> /dev/pts/14
lrwx------ 255 -> /dev/pts/14

Typically, all three are actually open read+write, so the `>&0` redirect 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 `stdout` and `stderr`, and for whatever reason you're not able to change that:

if [ ! -t /dev/fd/1 -a ! -t /dev/fd/2 -a -t /dev/fd/0 ]; then
    echo "My message that I really, really want to go to a terminal" >&0
fi

But I wouldn't recommend actually doing this.

Problem

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?

Original source