【问题标题】:whay print this when replace Linux file description [closed]替换Linux文件描述时为什么要打印这个[关闭]
【发布时间】:2020-09-20 14:21:34
【问题描述】:

为什么会得到不同的结果?分配变量a 时真正发生了什么

shell文件内容为


ls
a=`cat 2 3 1>/dev/pts/0 2>/proc/self/fd/1`
echo ------$a--------1
a=`cat 2 3  2>/proc/self/fd/1 1>/dev/pts/0`
echo ------$a--------2

当执行 shell 时,它会输出


[root@VM-0-17-centos ~]# sh test.sh 
2  dump.rdb  node-v12.18.3-linux-x64.tar.xz  test.sh
hello
cat: 3: No such file or directory
--------------1
hello
------cat: 3: No such file or directory--------2

【问题讨论】:

  • 你的问题真的很糟糕。请在您的问题中包含所有必要信息以及重现问题所需的所有步骤。请在发布前检查您的问题。请创建一个MCVE。请阅读how to ask a good question。我猜2文件的内容是hello

标签: linux shell


【解决方案1】:

事实:

  1. 重定向按顺序处理
  2. 重定向被复制
  3. 我猜2文件的内容是hello,打印在stdout上。
  4. 文件3 不存在,命令cat 在stderr 上打印cat: 3: No such file or directory

结论:

  • a=$(cat 2 3 1>/dev/pts/0 2>/proc/self/fd/1)
    • 1>/dev/pts/01 绑定到终端 pts/0(为什么不 /dev/tty??)我猜这是运行代码的终端。
    • 2>/proc/self/fd/12>&1,它也是一样的,因为 fd/1 现在连接到 pts/0,这也连接了 2>/dev/pts/0
    • a 为空,因为命令的 stdout 和 stderr 都直接打印到终端
  • a=$(cat 2 3 2>/proc/self/fd/1 1>/dev/pts/0)
    • 2>/proc/self/fd/12>&1 相同 - 将 stderr 连接到 stdout 指向的位置
    • 1>/dev/pts/0 将标准输出连接到 pts/0。请注意,fd 已复制 - 因此 stderr 不会更改并指向 stdout 指向的位置
    • 命令的标准输出在终端上可见(因此可见hello
    • 命令的stderr 连接到命令替换输出,所以它保存在a,所以cat: 3: No such file or directory 是可见的。

注意事项:

  • 使用http://shellcheck.net 检查您的脚本。
  • 不要使用反引号`。请改用$(...)
  • 引用您的变量扩展。
  • 使用/dev/tty 将输出重定向到控制终端,不要使用/proc/self/fd(也不要使用/dev/fd...),而是使用2>&1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多