歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux shell : Command 2>&1

Linux shell : Command 2>&1

日期:2017/2/28 15:43:41   编辑:SHELL編程

之前看到如下Linux hell 命令,一頭霧水:

ls temp >list.txt 2>&1
ls temp >/dev/null 2>&1

查閱之後,明白此語句含義,特此記錄.

ls temp >list.txt 2>&1 (ps:temp是個不存在的目錄)
ls temp >list.txt :
把標准輸出重定向到list.txt文件中,在這裡,就是把temp目錄下所有的文件,列出來,然後輸出到list.txt文件
如果沒有這個重定向,那麼標准輸出默認是控制台
標准輸出的句柄應該是1 ,所以,完整的寫法應該是:ls temp 1>list.txt

2>&1 :
在此處 ,表示把標准錯誤輸出寫入到list.txt文件
經過這個重定向,標准輸出和標准錯誤輸出都重定向到了list.txt中
結果如下:
root:ls temp >list.txt 2>&1
root:/opt/tmp # more list.txt
ls: cannot access temp: No such file or directory //error 信息在文件裡

ls temp >/dev/null 2>&1

這個表示把標准輸出,以及標准錯誤輸出都捨棄了,不顯示也不保存

如果換一下順序,如何?
ls temp 2>&1 >list.txt
標准錯誤輸出定向到控制台,標准內容輸出定向到list.txt
結果如下:
root:/opt/tmp # ls temp 2>&1 >out.txt
ls: cannot access temp: No such file or directory //error信息直接輸出到控制台

總結:
ls temp :表示標准內容輸出和標准錯誤都輸出到控制台
等同於:ls temp>&1
ls temp >list :表示標准內容輸出到list文件中,標准錯誤輸出還是在控制台
等同於:ls temp 1>list
ls temp >list 2>&1 :表示標准內容輸出到list文件中,標准錯誤輸出也在list文件中
等同於:ls temp >list 2>list
ls temp 1>list 2>list
ls temp 1>list 2>&1

ls temp 2>& >list :標准錯誤輸出也在控制台,表示標准內容輸出到list文件中
等同於:ls temp 2>& 1>list

Copyright © Linux教程網 All Rights Reserved