shell重定向的顺序问题

三个默认的文件描述符

0: stdin(标准输入)

1: stdout(标准输出)

2: stderr(标准错误输出)

系统中这3个文件描述符所对应的文件:

重定向顺序

示例脚本

echo "hello world"
echo "xxx"

sh test.sh

hello world
xxx

sh test.sh >/tmp/out

$ cat /tmp/out
hello world
xxx

sh -x test.sh >/tmp/out 2>/tmp/err

stdout和stderr分别被重定向到/tmp/out和/tmp/err。

$ cat /tmp/out
hello world
xxx
$ cat /tmp/err
+ echo 'hello world'
+ echo xxx

sh -x test.sh 2>&1 >/tmp/out

stdout被重定向到/tmp/out,stderr被重定向到stdout。因为在执行2>&1的时候,stdout对应的文件为/dev/pts/2,所以stderr的输出仍为stdout,后面的stdout被重定向到/tmp/out。

$ sh -x test.sh 2>&1 >/tmp/out
+ echo 'hello world'
+ echo xxx
$ cat /tmp/out
hello world
xxx

文件描述符、打开的文件句柄以及i-node之间的关系

img

总结

从左向右检查每个重定向,前面的重定向会影响后面的。

原文地址:https://www.cnblogs.com/jmliao/p/11561776.html