shell中>/dev/null 2>&1的含义

2016年1月10日10:35:21系统教程评论1,105

在Linux服务器的Crontab命令或shell脚本中经常会看到>/dev/null 2>&1写法,>/dev/null 2>&1的作用是什么呢?我们知道在unix/linux shell 中:文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

“>”(右尖括号)表示“输入到”的意思,就是把”>”左边的内容输入到”>”右边;文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

1 表示stdout标准输出,系统默认值是1;文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

2 表示stderr标准错误;& 表示等同于的意思,2>&1,表示2的输出重定向等同于1。文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

所以对于>/dev/null 2>&1我们可以分为两部分理解:文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

>/dev/null:文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

/dev/null代表空设备,>/dev/null 表示标准输出重定向到空设备文件,也就是不输出任何信息到终端,说白了就是不显示任何信息。文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

2>&1:文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

标准错误输出(2)重定向等同于标准输出(1),因为之前标准输出已经重定向到了空设备文件,所以2>&1表示标准错误输出也重定向到空设备文件。文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

通过以上两部分的理解,我们可以知道,在shell命令后面加>/dev/null 2>&1即不输出任何信息到终端,哪怕是错误信息也不输出。文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

延伸阅读:文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

为什么会写成类似command > file 2 > &1,而不直接写成command > file 2 > file呢?两种写法不都是把stdout标准输出和stderr标准错误输出到file文件吗?文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

首先command > file 2>file 的意思是将命令所产生的stdout标准输出信息和stderr错误的输出信息送到file 中。command > file 2>file 这样的写法,stdout和stderr都直接送到file中,file会被打开两次,这样stdout和stderr会互相覆盖,这样写相当使用了FD1和FD2两个同时去抢占file的管道。文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

而command >file 2>&1 这条命令就将stdout直接送向file,stderr 继承了FD1管道后,再被送往file,这种写法file文件只被打开了一次,即只使用了一个管道FD1就包括了stdout和stderr的内容。文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

从IO效率上,command >file 2>&1命令的效率要比command > file 2>file的命令效率高,所以在编写shell脚本时,我们较多时间使用command > file 2>&1的写法。文章源自堕落的鱼-https://www.duoluodeyu.com/2191.html

匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定