1. 程式人生 > >Shell的>/dev/null、2>&1、2>1

Shell的>/dev/null、2>&1、2>1

重新 test lan tdi 就是 顯示 tran mouse flat

轉載自:http://dos2unix.cn/link/480

1. 標準輸入stdin文件描述符為0,標準輸出stdout文件描述符為1,標準錯誤stderr文件描述符為2

2. /dev/null 空設備,相當於垃圾桶

3. 重定向符號:>

3. 2>1 與 2>&1 的區別

  • 2>1, 把標準錯誤stderr重定向到文件1中
  • 2>&1,把標準錯誤stderr重定向到標準輸出stdout

4. 舉例:

假設有腳本test.sh,內容如下,t是一個不存在的命令,執行腳本進行下面測試。

Shell
1 2 3 # cat test.sh
t date

標準輸出重定向到log,錯誤信息輸出到終端上,如下:

Shell
1 2 3 4 # ./test.sh > log ./test.sh: line 1: t: command not found # cat log Thu Oct 23 22:53:02 CST 2008

刪除log文件,重新執行,這次是把標準輸出定向到log,錯誤信息定向到文件1

Shell
1 2 3 4 5 6 7 # ./test.sh > log 2>1 # # cat log Thu Oct 23 22:56:20 CST 2008
# cat 1 ./test.sh: line 1: t: command not found #

把標準輸出重定向到log文件,把標準錯誤重定向到標準輸出,也就是把錯誤信息和輸出信息全都重定向到log裏面

Shell
1 2 3 4 5 6 # ./test.sh > log 2>&1 # # cat log ./test.sh: line 1: t: command not found Thu Oct 23 22:58:54 CST 2008 #

把錯誤信息重定向到空設備

Shell
1 2 3 # ./test.sh 2>/dev/null Thu Oct 23 23:01:07 CST 2008 #

把標準輸出重定向到空設備

Shell
1 2 3 # ./test.sh >/dev/null ./test.sh: line 1: t: command not found #

把標準輸出和標準錯誤全重定向到空設備

Shell
1 2 #./test.sh >/dev/null 2>&1 #

把標準輸出和標準錯誤全重定向到空設備

Shell
1 2 #./test.sh >/dev/null 2>&1 #

Shell的>/dev/null、2>&1、2>1