Unix/Linux 的重導向 (2>&1)
故意把 2>&1 寫在標題這樣應該比較多人能搜尋到吧,本文介紹 Linux 中的輸出重導向。
基本概念
File Descriptor (fd)
| fd | 名稱 | 預設目標 |
|---|---|---|
| 0 | stdin | 鍵盤輸入 |
| 1 | stdout | 終端機輸出 |
| 2 | stderr | 終端機輸出 |
符號
>: 輸出轉向(覆寫)>>: 輸出轉向(附加)<: 輸入轉向<<: Here Document,直到遇到指定字串才結束輸入&: 修飾後面的數字,表示 file descriptor 而非檔名|: pipe,把左側 stdout 接到右側 stdin,pipe 只傳遞 stdout
常用導向方式
> file: stdout 寫入 file(覆寫)>> file: stdout 寫入 file(附加)2>&1: stderr 轉向至 stdout(把2stderr 丟到&1,由於有&修飾,因此1代表 stdout 而非名為1的檔案)
同時導向 stdout + stderr
> file 2>&1: 兩者都寫入 file(覆寫)>> file 2>&1: 兩者都寫入 file(附加)&> file: 同> file 2>&1(Bash 簡寫,較新)&>> file: 同>> file 2>&1(Bash 簡寫,較新)
&> 是 bash 的語法糖,把 stdout 和 stderr 都重導向到同一目標。
順序陷阱
> file 2>&1 與 2>&1 > file 不同
> file 2>&1:先將 stdout 指向 file,再將 stderr 指向當前 stdout(即 file)→ 兩者都進 file2>&1 > file:先將 stderr 指向當前 stdout(終端機),再將 stdout 指向 file → stderr 仍在終端機
輸入
< file: 從 file 讀取作為 stdin<< EOF: Here Document,輸入直到遇到EOF
cat << EOF
line1
line2
EOF
重導向從左到右依序解析,&1 代表「此時此刻的 stdout」。
Pipe 與重導向並用
command 2>&1 | tee output.log
tee 同時輸出到終端機與檔案,常用於保留螢幕輸出又想存檔。
pipe 只傳遞 stdout,若要把 stderr 也送進 pipe,需先 2>&1。
Google Search 總喜歡把這種文章放到前面...