Linux 的檔案描述符是與輸入輸出相關的整數,最常見的是 stdin、stdout 與 stderr,分別對應 0、1、2。透過重定向,可把輸出、錯誤或輸入導向檔案或其他描述符。
echo "This is a sample text 1" > temp.txt echo "this is sample text 2" >> temp.txt cat temp.txt
> 會先清空目標檔案再寫入;>> 則會把內容附加到檔案末端。
若指令發生錯誤,訊息會走 stderr。可用 2> 將錯誤導向檔案:
ls + 2> out.txt cmd 2>stderr.txt 1>stdout.txt cmd 2>&1 output.txt cmd &> output.txt
若不想看到錯誤訊息,可導向 /dev/null:
some_command 2>/dev/null
tee 可把 stdin 同時送到螢幕與檔案:
command | tee FILE1 FILE2 cat a* | tee out.txt | cat -n
若需要把多行文字當作標準輸入,可使用 here-document。例如:
cat <log.txt LOG FILE HEADER This is a test log file EOF
掌握這些重定向技巧,就能更有效率地處理日誌、錯誤訊息與腳本輸出。