歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

Linux腳本之>/dev/null 2>&1,以及2>1 VS 2>&1

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是一個不存在的命令,執行腳本進行下面測試。
   # cat test.sh
     t
     date

   標准輸出重定向到log,錯誤信息輸出到終端上,如下:
   # ./test.sh > log
     ./test.sh: line 1: t: command not found
   # cat log
     Thu Oct 23 22:53:02 CST 2008
  
   刪除log文件,重新執行,這次是把標准輸出定向到log,錯誤信息定向到文件1
   # ./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文件,把標准錯誤重定向到標准輸出
   # ./test.sh > log 2>&1
   #
   # cat log
   ./test.sh: line 1: t: command not found
   Thu Oct 23 22:58:54 CST 2008
   #

   把錯誤信息重定向到空設備
   # ./test.sh 2>/dev/null
   Thu Oct 23 23:01:07 CST 2008
   #
  
   把標准輸出重定向到空設備
   # ./test.sh >/dev/null
     ./test.sh: line 1: t: command not found


   把標准輸出和標准錯誤全重定向到空設備
   #./test.sh >/dev/null 2>&1
   #

   把標准輸出和標准錯誤全重定向到空設備
   #./test.sh >/dev/null 2>&1

Copyright © Linux教程網 All Rights Reserved