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 資料流重導向完整指南:標準輸入/輸出/錯誤、檔案描述符、管線、Here Document、tee 分流

編輯:關於 Linux

資料流重導向是 Shell 腳本靈活處理輸入輸出的基石。本文系統整理 0/1/2 檔案描述符、>/>>/</<< 重導向符號、2>&1 合併錯誤輸出、tee 分流、exec 永久重導向、/dev/null 黑洞等核心技巧。

資料流重導向示意圖

三大標準資料流

FD裝置檔案說明
0/dev/stdin標準輸入 (鍵盤/管線上游)
1/dev/stdout標準輸出 (螢幕/管線下游)
2/dev/stderr標準錯誤 (螢幕,預設不經管線)

基礎重導向語法


cmd > file       # stdout 覆蓋寫入
cmd >> file      # stdout 追加寫入
cmd < file       # stdin 從檔案讀取
cmd 2> file      # stderr 寫入
cmd 2>&1         # stderr 合併到 stdout (須寫在 > file 之前)
cmd > file 2>&1  # 正確:stdout→file, stderr→stdout→file
cmd &> file      # Bash 簡寫:stdout+stderr 同寫入

Here Document / Here String


# Here Document (多行輸入)
cmd << 'EOF'
第一行
第二行 $VAR 不展開 (單引號 EOF)
EOF

cmd <<- EOF
    縮排的行首 Tab 會被忽略
EOF

# Here String (單行)
cmd <<< "single line input"

進階技巧


# tee 同時輸出螢幕與檔案
cmd | tee output.log
cmd | tee -a output.log   # 追加

# exec 永久重導向 (腳本內部)
exec 3> debug.log         # 開啟 FD 3
echo "debug" >&3
exec 3>&-                 # 關閉 FD 3

# 丟棄輸出
cmd > /dev/null 2>&1

# 交換 stdout/stderr (罕見但實用)
cmd 3>&1 1>&2 2>&3 3>&-

實戰範例:腳本同時記錄正常/錯誤日誌


#!/bin/bash
exec 1> >(tee -a /var/log/myscript.log)
exec 2> >(tee -a /var/log/myscript.err >&2)

echo "Normal output"
ls /nonexistent   # 產生錯誤輸出

掌握資料流重導向,即可編寫健壯、可觀測、易除錯的 Shell 自動化腳本。

Copyright © Windows教程網 All Rights Reserved