一、IO重定向和管道
stdin:standard? ?input? ? ?標準輸入
stdout:standard? output? 標準輸出
stderr: standard? error? ? 標準錯誤輸出
舉例
find? ?/etc/ -name? passwd? ?> find.out? ? ? ? ? ?將正確的輸出重定向在這個find.out文件中
find? ?/etc/ -name? passwd? ?2> find.err? ? ? ? ? 將錯誤輸出重定向這個find.err這個文件中
切記勿重定向覆蓋之前的文件,如果是追加的話,請使用 " >> " 這個符號
find? ?/etc/ -name? passwd? ?2 > > find.err? ?
find? ?/etc/ -name? passwd? ?2>? ?/dev/null? ? ? ? ? ? ? 將錯誤輸出重定向空文件當中
find? ?/etc/ -name? passwd? ?&>? ? ?find.text? ? ? ? ? ? &表示所有信息,都重定向到find.text文件中
find? ?/etc/ -name? passwd? ?2>&1? ? ?find.text? ? ? ? ?2>&1將錯誤信息當作正確信息輸出
I/O重定向與管道:LinuxShell的核心數據流控制
二、標準數據流(StandardStreams)
每個Linux命令運行時自動打開三個數據流:
|流名稱|文件描述符|默認來源/目標|用途|
|---------|------------|----------------|--------------------|
|stdin|0|鍵盤|命令的輸入數據|
|stdout|1|終端屏幕|命令的正常輸出|
|stderr|2|終端屏幕|命令的錯誤信息|
重定向的本質:改變這些數據流的來源或目標(從鍵盤/屏幕→文件/設備/其他命令)。
三、I/O重定向詳解
1.輸出重定向
|操作符|作用|示例|
|-------------|---------------------------------------|-------------------------------|
|>或1>|覆蓋寫入文件(stdout)|ls>file.txt|
|>>或1>>|追加到文件(stdout)|date>>log.txt|
|2>|覆蓋寫入錯誤到文件(stderr)|gcccode.c2>errors.log|
|2>>|追加錯誤到文件(stderr)|pinghost2>>network.err|
|&>|同時重定向stdout+stderr(覆蓋)|command&>output.log|
|&>>|同時重定向stdout+stderr(追加)|script.sh&>>debug.log|
2.輸入重定向
|操作符|作用|示例|
|--------|-------------------------------|-------------------------------|
|<|從文件讀取stdin|sort<unsorted.txt|
|<<|HereDocument(內聯文本)|見下方示例|
|<<<|HereString(字符串輸入)|grep"error"<<<"$message"|
HereDocument示例:
bash
mail-s"Reminder"user@example.com<<END
Hello!Meetingstartsat10AM.
Pleasebeontime.
END
3.高級用法
-重定向到文件描述符:
bash
將stderr合并到stdout
command2>&1>output.log
交換stdout和stderr
command3>&11>&22>&3
-丟棄輸出(黑洞設備):
bash
command>/dev/null丟棄stdout
command2>/dev/null丟棄stderr
command&>/dev/null丟棄所有輸出
---
四、管道(Pipe):|
作用:將一個命令的stdout作為下一個命令的stdin。
|示例命令|說明|
|-----------------------------------|------------------------------------------|
|ls-l\|grep".txt"|列出文件并過濾出.txt文件|
|psaux\|sort-nk4|查看進程并按內存使用排序|
|cataccess.log\|cut-d''-f1\|sort\|uniq-c|統計日志中每個IP的訪問次數|
管道vs重定向
|特性|管道(\|)|重定向(>,<)|
|------------|------------------------|------------------------|
|數據方向|命令→命令|命令?文件/設備|
|數據流|只傳遞stdout|可控制stdin/stdout/stderr|
|使用場景|命令鏈式處理|輸入/輸出到持久化存儲|
---
五、關鍵應用場景
1.日志處理
bash
grep"ERROR"/var/log/syslog|awk'{print$5}'>errors.txt
2.數據轉換
bash
echo"helloworld"|tr'a-z''A-Z'輸出:HELLOWORLD
3.實時監控
bash
tail-f/var/log/nginx/access.log|grep"404"
4.錯誤隔離
bash
保存正常輸出,丟棄錯誤
makebuild2>/dev/null|teebuild.log
5.多步驟分析
bash
netstat-tuln|grep":80"|awk'{print$5}'|cut-d:-f1
---
六、最佳實踐與注意事項
1.順序敏感:
command2>&1>file和command>file2>&1作用不同(后者正確)。
2.管道錯誤處理:
默認管道只傳遞stdout,需顯式合并錯誤流:
bash
command2>&1|less
3.避免覆蓋重要文件:
使用>file前確認文件可覆蓋,或用set-onoclobber禁止覆蓋。
4.管道中斷:
用tee同時查看和保存管道數據:
bash
dmesg|teeboot.log|grep"USB"
5.性能考量:
避免對大數據集使用多次管道,改用awk單次處理:
bash
低效:catbigfile|grep"x"|wc-l
高效:grep"x"bigfile|wc-l
>Linux哲學精髓:通過管道和重定向組合小工具(如grep,sort,awk),實現復雜任務。例如統計詞頻:
>bash
>catbook.txt|tr'''\n'|sort|uniq-c|sort-nr