? ganiks@bash-redirection cat 123 111111112222222233333333? ganiks@bash-redirection cat 123 >> abc ? ganiks@bash-redirection echo "one line" >> abc#當cat不帶參數的時候,表示使用標準輸入作為輸入,這允許在標準輸入中鍵入相關的內容? ganiks@bash-redirection cat >> abc444444445555555566666666^C # ctrl+C? ganiks@bash-redirection cat abc 111111112222222233333333one line444444445555555566666666
參考文檔
stderr to stdout? ganiks@bash-redirection cat > find.sh find . -name "*" -PRint -exec grep "555" {} /;^C? ganiks@bash-redirection sudo chmod +x find.sh? ganiks@bash-redirection ./find.sh .grep: .: 是一個目錄./abc55555555./nginx-V./find.shfind . -name "*" -print -exec grep "555" {} /;./123#第一種情況? ganiks@bash-redirection ./find.sh 2>&1 > find1.loggrep: .: 是一個目錄grep: 輸入文件 ‘./find1.log’ 同時也作輸出#第一種情況? ganiks@bash-redirection ./find.sh > find2.log 2>&1#結果1? ganiks@bash-redirection cat find1.log ../abc55555555./nginx-V./find.shfind . -name "*" -print -exec grep "555" {} /;./123./find1.log#結果2 ? ganiks@bash-redirection cat find2.log .grep: .: 是一個目錄./abc55555555./nginx-V./find.shfind . -name "*" -print -exec grep "555" {} /;./123./find1.log55555555find . -name "*" -print -exec grep "555" {} /;./find2.loggrep: 輸入文件 ‘./find2.log’ 同時也作輸出
0 是 stdin1 是 stdout2 是 stderr
? ./find.sh 2>&1 > find1.log? ./find.sh > find2.log 2>&1
這里分析的關鍵是:一步一步分析,分析一步,輸出一步
第一種情況:
>find1.log
: 將stdout 再重定向到文件第二種情況:
>find2.log
: 將stdout重定向到文件基本的IO重定向重定向的過程其實很簡單,但由于和直觀感受不一致,往往導致初學者在這里犯很多錯誤。 參考文檔
基本IO重定向操作
> file
: 將stdout重定向到file>>file
:將標準輸出重定向到file,如果file存在,append到文件中,即附加到文件的后面,而不是覆蓋文件> | file
: 強制將標準輸出重定向到file,即使noclobber設置。當設置環境變量set –o noclobber,將禁止重定向到一個已經存在的文件中,避免文件被覆蓋。? ganiks@bash-redirection cat >> msgfile <<.heredoc> this is the text ofheredoc> our messageheredoc> end with .heredoc> . #這里<<.表明以.為結束。因此無需使用^D,而改用. ? ganiks@bash-redirection cat msgfile this is the text ofour messageend with .
>&-
: 關閉標準輸出文件描述符在bash中比較少用,從0開始用戶表示進行的數據流,0表示標準輸入,1表示標準輸出,2表示標注錯誤輸出,其他從3開始。最為常用的場景是將錯誤消息輸出到某個文件,可以加上2>file 到我們的命令中?! ∥覀儊砜聪旅嬉粋€腳本的例子:
command > logfile 2>&1 &
>logfile
表示command的標準輸出重定向至文件logfile中下面可達到類似的效果:
command 2>&1 | tee logfile &
錯誤輸出同樣適用標準輸出,通過pipe方式,見他們作為輸入執行tee logfile。tee命令將它的標準輸入copy至他的標準標準輸出以及參數所帶的文件中。和上面的命令不一眼這里即會在stdout 和logfile中同時輸出。
其他文件描述字的重定向,例如<&n,通常用于從多個文件中讀入或者寫出。
>&-
,表示強制關閉標準輸出新聞熱點
疑難解答