把/dev/null看作"黑洞". 它非常等价于一个只写文件. 所有写入它的内容都会永远丢失. 而尝试从它那儿读取内容则什么也读不到. 然而, /dev/null对命令行和脚本都非常的有用.
禁止标准输出.
1 cat $filename >/dev/null 2 # 文件内容丢失,而不会输出到标准输出. |
禁止标准错误
1 rm $badname 2>/dev/null 2 # 这样错误信息[标准错误]就被丢到太平洋去了. |
禁止标准输出和标准错误的输出.
1 cat $filename 2>/dev/null >/dev/null 2 # 如果"$filename"不存在,将不会有任何错误信息提示. 3 # 如果"$filename"存在, 文件的内容不会打印到标准输出. 4 # 因此Therefore, 上面的代码根本不会输出任何信息. 5 # 当只想测试命令的退出码而不想有任何输出时非常有用。 6 #-----------测试命令的退出 begin ----------------------# 7 # ls dddd 2>/dev/null 8 8 # echo $? //输出命令退出代码:0为命令正常执行,1-255为有出错。 9 #-----------测试命令的退出 end-----------# 10# cat $filename &>/dev/null 11 # 也可以, 由 Baris Cicek 指出. |
清除日志文件内容
1 cat /dev/null > /var/log/messages 2 # : > /var/log/messages 有同样的效果, 但不会产生新的进程.(因为:是内建的) 3 4 cat /dev/null > /var/log/wtmp |
例子 28-1. 隐藏cookie而不再使用
1 if [ -f ~/.netscape/cookies ] # 如果存在则删除. 2 then 3 rm -f ~/.netscape/cookies 4 fi 5 6 ln -s /dev/null ~/.netscape/cookies 7 # 现在所有的cookies都会丢入黑洞而不会保存在磁盘上了. |
今天一个朋友突然在自己的维护的Linux中, /var/spool/cron/root 中看到了以下的内容:
30 19 * * * /usr/bin/**dcon.sh > /dev/null 2>&1
59 23 * * 1-7 /home/s**-log/squid-log.renew > /dev/null 2>&1
50 1 * * 1-7 /usr/local/src/**log.sh > /dev/null 2>&1
20 2 * * 1-7 /home/sq**-log/**log > /dev/null 2>&1
30 2 * * 1-7 /home/sq**-log/**log.01
30 22 * * * /bin/**sync > /dev/null 2>&1
00 8 * * 1-7 /home/**-log/rmcore > /dev/null 2>&1
00 16 * * 1-7 /home/**-log/rmcore > /dev/null 2>&1
他问我为什么要用 /dev/null 2>&1 这样的写法.这条命令的意思是将标准输出和错误输出全部重定向到/dev/null中,也就是将产生的所有信息丢弃.下面我就为大家来说一下, command > file 2>file 与command > file 2>&1 有什么不同的地方.
59 23 * * 1-7 /home/s**-log/squid-log.renew > /dev/null 2>&1
50 1 * * 1-7 /usr/local/src/**log.sh > /dev/null 2>&1
20 2 * * 1-7 /home/sq**-log/**log > /dev/null 2>&1
30 2 * * 1-7 /home/sq**-log/**log.01
30 22 * * * /bin/**sync > /dev/null 2>&1
00 8 * * 1-7 /home/**-log/rmcore > /dev/null 2>&1
00 16 * * 1-7 /home/**-log/rmcore > /dev/null 2>&1
他问我为什么要用 /dev/null 2>&1 这样的写法.这条命令的意思是将标准输出和错误输出全部重定向到/dev/null中,也就是将产生的所有信息丢弃.下面我就为大家来说一下, command > file 2>file 与command > file 2>&1 有什么不同的地方.
首先~command > file 2>file 的意思是将命令所产生的标准输出信息,和错误的输出信息送到file 中.command > file 2>file 这样的写法,stdout和stderr都直接送到file中, file会被打开两次,这样stdout和stderr会互相覆盖,这样写相当使用了FD1和FD2两个同时去抢占file 的管道.
而command >file 2>&1 这条命令就将stdout直接送向file, stderr 继承了FD1管道后,再被送往file,此时,file 只被打开了一次,也只使用了一个管道FD1,它包括了stdout和stderr的内容.
从IO效率上,前一条命令的效率要比后面一条的命令效率要低,所以在编写shell脚本的时候,较多的时候我们会用command > file 2>&1 这样的写法.