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 Shell 重定向與管道完全指南:標準輸入/輸出/錯誤控制實戰

編輯:Linux 教學

重定向基礎概念

Linux 中每個進程預設開啟三個檔案描述符:

  • 0 - stdin(標準輸入,預設鍵盤)
  • 1 - stdout(標準輸出,預設螢幕)
  • 2 - stderr(標準錯誤,預設螢幕)

重定向即改變這些描述符指向的目標(檔案、裝置或另一程式)。

輸出重定向

語法說明範例
cmd > file標準輸出導向檔案(覆蓋)ls -l > list.txt
cmd >> file標準輸出追加到檔案echo "new line" >> log.txt
cmd 1> file同 cmd > file(明確指定 fd 1)find / -name "*.conf" 1> result.txt
cmd 2> file標準錯誤導向檔案(覆蓋)gcc test.c 2> error.log
cmd 2>> file標準錯誤追加到檔案make 2>> build.err
cmd > file 2>&1stdout 與 stderr 合併導向檔案(覆蓋)./run.sh > all.log 2>&1
cmd >> file 2>&1stdout 與 stderr 合併追加./daemon.sh >> daemon.log 2>&1
cmd &> fileBash 簡寫:合併 stdout/stderr 覆蓋python3 script.py &> output.txt
cmd &>> fileBash 簡寫:合併追加./test &>> test.log

輸入重定向

語法說明範例
cmd < file從檔案讀取標準輸入sort < unsorted.txt
cmd << EOF ... EOFHere Document:從標準輸入讀取直到分隔符cat << EOF > file.txt
line1
line2
EOF
cmd <<< "string"Here String:直接提供字串作為輸入tr a-z A-Z <<< "hello"

進階技巧

檔案描述符操作

# 將 fd 3 指向檔案
exec 3> output.txt
echo "test" >&3
exec 3>&-  # 關閉 fd 3

# 交換 stdout 與 stderr
cmd 3>&1 1>&2 2>&3

tee 同時輸出螢幕與檔案

./build.sh 2>&1 | tee build.log

原文中錯誤修正

  • 命令>! 文件:!csh 強制覆蓋語法,Bash 不支援,請用 >| 或直接 >(若設定 set -o noclobber)。
  • 命令>& 文件:csh 語法,Bash 請用 &> 或 > file 2>&1。
  • command filename2:原文殘缺,應為 cmd < file1 > file2。

最佳實踐建議

  • 腳本中明確使用 1> 2> 增加可讀性。
  • 錯誤日誌與正常輸出分離,便於監控與分析。
  • 長期運行的服務建議使用 logrotate 管理日誌檔案大小。
Copyright © Windows教程網 All Rights Reserved