1

Can someone please explain how these process substitutions are working.

(echo "YES")> >(read str; echo "1:${str}:first";)> >(read sstr; echo "2:$sstr:two")> >(read ssstr; echo "3:$ssstr:three")

Output

1:2:3:YES:three:two:first

I've figured out, that the 'ssstr'-Substitution got FD 60, sstr FD 61 and str FD 62. (right to left)

But how is (echo "YES") connected to input of FD60, and output of FD60 with input FD61 and so on and finally FD62 prints out on Terminal ?

All against the direction of the two redirections.

How are they nested, and how connected ? Makes me crazy. Ty.

4

1 回答 1

2

首先,不要真的写这样的代码:)

过程替换是构造>(...)(...)>不是特定的构造;它只是一个子shell,后跟一个输出重定向。

此示例是一个命令(echo "YES"),后跟三个输出重定向

  1. > >(read str; echo "1:${str}:first";)
  2. > >(read sstr; echo "2:$sstr:two")
  3. > >(read ssstr; echo "3:$ssstr:three")

最后一个是实际应用于原始命令的那个;类似的东西echo word >foo >bar >baz会创建所有三个文件,但输出echo只会写入baz.

同样,所有三个进程替换都会启动一个新进程,但输出YES只写入最后一个。所以read ssstrecho YES.

在这一点上,我认为您看到的是未定义的行为。三个进程替换以它们创建的相反顺序运行,就好像操作系统在创建下一个进程时将每个进程推入堆栈,然后通过将它们从堆栈中弹出来安排它们,但我不认为这个顺序是任何东西都可以保证。

但是,在每种情况下,每个进程替换的标准输入都固定为命令的标准输出,即刚刚运行的其他进程替换。换句话说,该命令最终类似于

echo YES | { 
  read ssstr
  echo "3:$ssstr:three" | {
    read sstr
    echo "2:$sstr:two" | {
      read str
      echo "1:$str:one"
    }
  }
}
于 2016-11-19T13:22:23.917 回答