对于有使用'>&安培; 0(重定向到标准输入)? [英] are there uses for '>&0' (redirect to stdin)?

查看:139
本文介绍了对于有使用'>&安培; 0(重定向到标准输入)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash,那么你可以这样做:

In bash you can do:


  • 回声试验>&放大器; 1 (重定向到stdout,虽然它已经去那里)

  • 回声试验>和2 (重定向标准错误)

  • 回声试验>&安培; 0 (重定向到标准输入)

  • 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?

推荐答案

要更precise,是什么>&安培; 0 做的是重复的文件描述符0作为文件描述符1.如果程序的标准输入只开放阅读,那么当你的程序试图写入stdout(文件描述符1),因为文件描述符1也只开放阅读它会得到一个错误。

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.

您可以通过编写一个小的shell脚本,检查自己的文件描述符证明这一点:

You can demonstrate this by writing a small shell script that inspects its own file descriptors:

10156115.sh:

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

其结果是,你在下面的标准错误

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

通常情况下,所有这三个实际上是开放的读和写,因此&GT;&安培; 0 重定向没有任何效果可言,如果从正常的外壳单独使用

Typically, all three are actually open read+write, so the >&0 redirect has no effect at all if used alone from a normal shell.

有什么用途呢?

有没有这个共同的任何用途,但如果任何人调用脚本重定向标准输出和标准错误,并为你无论出于何种原因无法更改:

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.

这篇关于对于有使用'&GT;&安培; 0(重定向到标准输入)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆