Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 文本流與 I/O 重定向管道核心機制詳解

編輯:關於 Linux

「一切皆字節流」是 Unix/Linux 的核心哲學。標準輸入、標準輸出、標準錯誤三大流、重定向、管道構成了 Shell 腳本與命令行組合操作的血管系統。本文深度剖析流模型、文件描述符、重定向語法、管道原理、實戰組合技。

一、流模型:字節流即介面

  • 數據在內存、文件、設備、進程間流動的統一抽象:位元組序列。
  • 文本流 = 可讀字符流 (ASCII/UTF-8);二進制流 = 任意字節 (圖片、可執行文件)。
  • Linux 不區分文本/二進制文件,統一按字節處理,由上層應用賦予語義。

二、三大標準流與文件描述符 (FD)

名稱FD默認連接用途
標準輸入 (stdin)0鍵盤/終端程序讀取數據來源
標準輸出 (stdout)1屏幕/終端程序正常結果輸出
標準錯誤 (stderr)2屏幕/終端診斷、警告、錯誤信息

進程啟動時內核自動打開 FD 0/1/2。Shell 通過 dup2() 系統調用重新綁定它們至文件/管道/設備。

三、重定向:改變流的流向

1. 輸出重定向

cmd > file      # 覆蓋寫入 stdout 到文件 (1> 同義)
cmd >> file     # 追加寫入 stdout
cmd 2> file     # 覆蓋寫入 stderr
cmd 2>> file    # 追加寫入 stderr
cmd &> file     # 同時重定向 stdout 和 stderr (覆蓋)
cmd &>> file    # 同時追加 stdout 和 stderr
cmd > file 2>&1 # 經典寫法:stdout→file, stderr→stdout(即file) 【順序關鍵】
cmd > file 2>&1 等價於 cmd &> file

2. 輸入重定向

cmd < file      # 從文件讀取 stdin
cmd << 'EOF'    # Here Document:內嵌多行輸入,以 EOF 結束
cat << EOF > script.sh
#!/bin/bash
echo "Hello"
EOF
cmd <<< "string" # Here String:單字符串作為 stdin (Bash/Zsh)

3. 文件描述符操作進階

exec 3> log.txt       # 打開 FD 3 寫入文件
echo "debug" >&3  # 寫入 FD 3
exec 3>&-         # 關閉 FD 3

exec 4< input.txt # 打開 FD 4 讀取
read line <&4
exec 4<&-         # 關閉 FD 4

四、管道:進程間流水線

  • cmd1 | cmd2:內核創建管道 (管道 inode,無實體文件),將 cmd1 的 stdout (FD1) 連接管道寫端,cmd2 的 stdin (FD0) 連接管道讀端。
  • 數據在內核緩衝區流動 (默認 64KB),無磁盤 I/O,極快。
  • 多級管道:cmd1 | cmd2 | cmd3 形成流水線,並發運行。
  • |& (Bash/Zsh) = 2>&1 |:同時管道 stdout 和 stderr。

五、核心文本處理三劍客 + tee

命令功能典型管道用法
cat拼接/輸出文件內容cat file | grep pattern
echo輸出字符串echo "path" | xargs rm
wc統計行/詞/字節 (-l/-w/-c)cat file | wc -l
tee讀 stdin,同時寫 stdout 和文件cmd | tee log.txt | grep error

tee -a 追加模式;tee - 輸出兩次到 stdout (調試用)。

六、實戰組合招

# 1. 查找包含 error 的日志行數,並保存匹配行
grep "error" app.log | tee errors.txt | wc -l

# 2. 統計當前目錄下各類文件數量
find . -type f -name "*.*" | sed 's/.*\.//' | sort | uniq -c | sort -rn

# 3. 監控 nginx 訪問日志實時提取 4xx/5xx 狀態碼
tail -f /var/log/nginx/access.log | awk '$9 ~ /^[45]/ {print $0}'

# 4. 將命令結果既顯示又存檔,且捕獲 stderr
make 2>&1 | tee build.log

# 5. 使用進程替換 (Process Substitution) 實現多輸出
diff <(cmd1) <(cmd2)  # 比較兩命令輸出,無需臨時文件

七、總結

文本流機制賦予了 Linux 極強的組合性:標準流 (0/1/2) + 重定向 (><) + 管道 (|) + 文本工具 = 無限可能。熟練掌握 FD 操作、Here Doc、tee、進程替換,能讓 Shell 腳本從「能跑」進化為「健壯、高效、可維護」。

Linux 文本流重定向管道示意圖

Copyright © Windows教程網 All Rights Reserved