2>&1 的使用方法
1 :表示stdout标准输出,系统默认值是1
2 :表示stderr标准错误
& :表示等同于的意思,2>&1,表示2的输出重定向等同于1
[root@hecs-98663 myshell]# cat test.sh
echo 111
aaa
[root@hecs-98663 myshell]# bash test.sh > result
test.sh:行2: aaa: 未找到命令
[root@hecs-98663 myshell]# cat result
111
[root@hecs-98663 myshell]# bash test.sh 2> error
111
[root@hecs-98663 myshell]# cat error
test.sh:行2: aaa: 未找到命令
#要连续打开两次文件,效率慢
[root@hecs-98663 myshell]# bash test.sh >> k 2>> k
[root@hecs-98663 myshell]# cat k
111
test.sh:行2: aaa: 未找到命令
#2>&1 :的意思就是将标准错误也输出到标准输出当中,从而一起打到文件中
[root@hecs-98663 myshell]# cat result
[root@hecs-98663 myshell]# bash test.sh 2>&1 result
111
test.sh:行2: xxx: 未找到命令
[root@hecs-98663 myshell]# cat result
[root@hecs-98663 myshell]# bash test.sh > result 2>&1
[root@hecs-98663 myshell]# cat test.sh
echo 111
xxx
shell中可能经常能看到:>/dev/null 2>&1
分解这个组合:“>/dev/null 2>&1” 为五部分:
1:> 代表重定向到哪里,例如:echo "123" > /home/123.txt
2:/dev/null 代表空设备文件
3:2> 表示stderr标准错误
4:& 表示等同于的意思,2>&1,表示2的输出重定向等同于1
5:1 表示stdout标准输出,系统默认值是1,所以">/dev/null" = "1>/dev/null"
因此,>/dev/null 2>&1也可以写成“1> /dev/null 2> &1”
执行过程为:
1、 1>/dev/null :首先表示标准输出重定向到空设备文件,即不输出任何信息到终端
2、 2>&1 :接着,标准错误输出重定向 到标准输出,因为之前标准输出已经重定向到了
空设备文件,所以标准错误输出也重定向到空设备文件。
还有两种写法
[root@hecs-98663 myshell]# bash test.sh >& b
[root@hecs-98663 myshell]# cat b
111
test.sh:行2: xxx: 未找到命令
[root@hecs-98663 myshell]# bash test.sh &> a
[root@hecs-98663 myshell]# cat a
111
test.sh:行2: xxx: 未找到命令

浙公网安备 33010602011771号