linux 重定向

執行指令,由檔案讀入資料,經過處理將資料輸出到屏幕。
讀入資料,叫做standard input, 資料輸出到屏幕,叫做standard output或standard error output。
輸出到屏幕分爲兩種,指令執行成功,叫做standard output, 執行失敗,叫做standard error output,這兩種都會輸出到屏幕。

爲了將這兩種輸出分開,可以使用資料重定向功能,將輸出傳輸到其他檔案中。

(單箭頭表示覆蓋,雙箭頭表示增加)
stdout: 使用>或>>,符合爲1
stderr: 使用2>或2>>,符號爲0

例如 ll / > /home/text.txt 就將本應該在屏幕顯示的內容,都寫入到/home/text.txt文檔中,屏幕上沒有任何顯示了
使用find /home -name .bashrc 時,屏幕輸出
find: “/home/bbip”: 權限不夠
/home/leadcom/.bashrc
find: “/home/lost+found”: 權限不夠
其中有正確輸出,也有錯誤輸出
如果只使用stdout,會將正確輸出指定到文件,錯誤輸出仍顯示在屏幕
find /home -name .bashrc > /home/find_test.txt
要想將正確輸出和錯誤輸出都指定到文件,則stdout和stderr都使用
find /home -name .bashrc >/home/find_test.txt 2>/home/find_test_err.txt

如果想在屏幕上不顯示錯誤信息,則可以將錯誤信息重定向到/dev/null
find /home -name .bashrc 2>/dev/null
如果想將正確和錯誤信息都寫入一個文件,且保證原來的順序,則使用特殊寫法
find /home -name .bashrc > /home/find_test_all.txt 2>&1 (注意是在原來stdout的寫法最後增加2>&1表達式)
或者find /home -name .bashrc &> /home/find_test_all.txt (注意是在原來stdout的寫法中間增加&符)

有輸出,就會有輸入,它代表將原本由鍵盤輸入的資料,改爲由檔案內容來取代
(單箭頭表示指定輸入文件,雙箭頭表示結束字符)
stdin: 使用<或者<<,符號爲0

什麼是鍵盤輸入
cat > /home/catfile, 執行後用鍵盤輸入testing,按ctrl+d,就會將鍵盤輸入的testing字符寫入文件中
若想用文檔內容替換鍵盤輸入,使用stdin:
cat > /home/catfile < /home/leadcom/.bashrc
執行後就將/home/leadcom/.bashrc的內容寫入到/home/catfile中
cat > /home/catfile << eof
表示檢測到eof字符時,結束輸入

發佈了34 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章