Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 標準輸出與錯誤輸出管理:重定向、管道與 tee 實作

標準輸出與標準錯誤

Linux 中正確輸出通常對應檔案描述符 1,錯誤輸出對應 2。以 find 搜尋 /etc 時,權限不足會產生錯誤訊息。

find /etc -name passwd

重定向

find /etc -name passwd > file
find /etc -name passwd 2> file
find /etc -name passwd &&> file

單獨 > 會覆蓋原檔;使用 >> 則是追加。

find /etc -name passwd >> file
find /etc -name passwd 2>> file
find /etc -name passwd &&>> file

管道與 tee

管道可把前一個命令的輸出交給後一個命令,但標準錯誤預設不會進入管道。可用 2>&1 把錯誤輸出併入標準輸出。

ls /bin | wc -l
find /etc -name passwd 2>&1 | tee file

檔案內容查詢

若要找出包含特定字串的內容,通常使用 grep 而非 find:

grep ich /usr/share/mime/packages/freedesktop.org.xml

練習重點

常見題目會要求分別保存正確輸出、錯誤輸出、全部輸出,或清空、追加檔案。例如:

find /etc -name passwd > /mnt/find.out 2> /mnt/find.err
find /etc -name passwd &&> /mnt/find.all
find /etc -name passwd &&>> /mnt/find.all
Copyright © Linux教程網 All Rights Reserved