/dev/null的作用

原創作品,允許轉載,轉載時請務必以超鏈接形式標明文章 原始出處 、作者信息和本聲明。否則將追究法律責任。http://viplin.blog.51cto.com/241472/99568
今天一個朋友突然在自己的維護的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 有什麼不同的地方.
首先~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 這樣的寫法.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章