Linux重定向

2020-01-30 11:25:54于海丽


(ls you no 2>&1;ls yes 2>&1) 2>&1|egrep * >file 
(ls you no 2>&1;ls yes 2>&1)|egrep * >file
(ls you no;ls yes) 2>&1|egrep * >file

这个例子要注意的就是:

理 解 命令执行顺序 和 管道“|”:在命令执行前,先要进行重定向的处理,并将把 nested sub-shell 的stdout 接到 egrep 命令的 stdin。 nested sub-shell ,在 ( ) 中的两个命令加上(),可以看作一个命令。其 FD1 已经连接到“|”往egrep送了,当遇到 2>&1时,也就是FD2=FD1,即FD2同FD1一样,往管道 “|”那边送。

b、 没有任何东西通过管道送给egrep,全部送往monitor。 (ls you no 2>&1;ls yes 2>&1) >&2|egrep * >file。虽然在()里面将 FD2转往FD1,但在()外,遇到 >&2 ,结果所有的都送到monitor。 请理解:


(ls you no 2>&1) 1>&2|egrep * >file ## 送到 monitor 
ls you no 2>&1 1>&2|egrep * >file ## 送给 管道 “|”
ls you no 1>&2 2>&1|egrep * >file ## 送到 monitor

5、 中阶例子

条件: stderr通过管道送给egrep,正确消息仍然送给monitor(不变)


exec 4>&1;(ls you no 2>&1 1>&4 4>&-;ls yes 2>&1 1>
&4 4>&-)|egrep * >file;exec 4>&-
或者
exec 4>&1;(ls you no;ls yes) 2>&1 1>
&4 4>&-|egrep * >file;exec 4>&-

如果加两个条件:

(1)要求cmd1和cmd2并行运行;

(2)将cmd1的返回值赋给变量 ss。

则为: