command>/dev/null 2>&1 &
这样形式的命令。那么2>&1到底是什么含义?其实这条命令是一个缩写版,对于一个重定向命令,肯定是command > a这种形式,它默认等于command 1>a,即将标准输出结果重定向到文件a中。所以command > /dev/null相当于执行了command 1 > /dev/null。执行command产生了标准输出stdout(用1表示),重定向到/dev/null的设备文件中。
通过上面command > /dev/null等价于command 1 > /dev/null,那么对于2>&1也就好理解了,2就是标准错误,1是标准输出,那么这条命令不就是相当于把标准错误重定向到标准输出么。但是是&1而不是1,这里&是什么?这里&相当于等效于标准输出。
我们编写一个脚本用于测试
[root@web1 ~]# vi a
#!/bin/bash
date
cc
我们正常执行脚本的话会输出date的结果和识别不到cc的错误信息
[root@web1 ~]# sh a
Fri Aug 9 17:13:33 CST 2019
a: line 3: cc: command not found
那么sh a >file 2>1
和sh a >file 2>&1
有什么区别呢?
[root@web1 ~]# sh a > file 2>1
[root@web1 ~]# cat file
Fri Aug 9 17:17:40 CST 2019
[root@web1 ~]# cat 1
a: line 3: cc: command not found
[root@web1 ~]# ls
1 2 a anaconda-ks.cfg c epel-release-latest-7.noarch.rpm file
可以看到不加&的话,会将脚本a的执行结果重定向到file中,然后将错误的输出重定向到文件1中,这里的1成了文件,而不是把标准错误重定向到标准输出。
[root@web1 ~]# sh a > file 2>&1
[root@web1 ~]# cat file
Fri Aug 9 17:23:55 CST 2019
a: line 3: cc: command not found
而加上&后则将标准错误重定向到标准输出,这样就可以把错误的输出也当作标准输出一块重定向到文件file中。
通过上面的分析,对于command>file 2>&1这条命令,等价于command 1>file 2>&1可以理解为执行command产生的标准输入重定向到文件file中,标准错误也重定向到文件file中。那么是否就说command 1>file 2>&1等价于command 1>file 2>file呢。
他们两个是有区别的,区别就在于前者只打开一次文件file,后者会打开文件两次,并导致stdout被stderr覆盖。从IO效率上来讲,command 1>fiile 2>&1比command 1>file 2>file的效率更高。
我们还是用上面那个脚本a做测试
[root@web1 ~]# sh a > file
a: line 3: cc: command not found
[root@web1 ~]# cat file
Fri Aug 9 17:37:42 CST 2019
可以看到正确输出被重定向到file中,而错误则被打印在屏幕上,这也进一步说明command > a这种形式,它默认等于command 1>a。
然后我们来测试command>file 2>file 与 command>file 2>&1的区别
[root@web1 ~]# sh a 1>file 2>file
You have new mail in /var/spool/mail/root
[root@web1 ~]# cat file
a: line 3: cc: command not found
[root@web1 ~]# sh a 1>file 2>&1
[root@web1 ~]# cat file
Fri Aug 9 17:41:50 CST 2019
a: line 3: cc: command not found
可以看到当执行sh a 1>file 2>file
时,file中只有错误的输出,因为这种格式,文件被打开了两次,导致标准输出被后面的错误输出覆盖了。而当执行sh a 1>file 2>&1
时,标准输出与错误输出都被重定向到file中。
除此之外,我们还可通过&>file将标准输出和错误重定向到file文件。这样的写法更方便。
[root@web1 ~]# sh a &>file
[root@web1 ~]# cat file
Fri Aug 9 17:55:15 CST 2019
a: line 3: cc: command not found