經常可以在一些腳本,尤其是在crontab調用時發現如下形式的命令調用
/tmp/test.sh > /tmp/test.log 2>&1
前半部分/tmp/test.sh > /tmp/test.log很容易理解,那麼後面的2>&1是怎麼回事呢?
要解釋這個問題,還是得提到文件重定向。我們知道>和<是文件重定向符。那麼1和2是什麼?在shell中,每個進程都和三個系統文件相關聯:標準輸入stdin,標準輸出stdout和標準錯誤stderr,三個系統文件的文件描述符分別爲0,1和2。所以這裏2>&1的意思就是將標準錯誤也輸出到標準輸出當中。
下面通過一個例子來展示2>&1有什麼作用:
$ cat test.sh
t
date
t
date
test.sh中包含兩個命令,其中t是一個不存在的命令,執行會報錯,默認情況下,錯誤會輸出到stderr。date則能正確執行,並且輸出時間信息,默認輸出到stdout
./test.sh > test1.log
./test.sh: line 1: t: command not found
$ cat test1.log
Tue Oct 9 20:51:50 CST 2007
./test.sh: line 1: t: command not found
$ cat test1.log
Tue Oct 9 20:51:50 CST 2007
可以看到,date的執行結果被重定向到log文件中了,而t無法執行的錯誤則只打印在屏幕上。
$ ./test.sh > test2.log 2>&1
$ cat test2.log
./test.sh: line 1: t: command not found
Tue Oct 9 20:53:44 CST 2007
$ cat test2.log
./test.sh: line 1: t: command not found
Tue Oct 9 20:53:44 CST 2007
這次,stderr和stdout的內容都被重定向到log文件中了。
實際上, > 就相當於 1> 也就是重定向標準輸出,不包括標準錯誤。通過2>&1,就將標準錯誤重定向到標準輸出了,那麼再使用>重定向就會將標準輸出和標準錯誤信息一同重定向了。如果只想重定向標準錯誤到文件中,則可以使用2> file。