天天看點

重定向 1>&2 2>&1

當初在shell中, 看到">&1"和">&2"始終不明白什麼意思.經過在網上的搜尋得以解惑.其實這是兩種輸出. 

在 shell 程式中,最常使用的 FD (file descriptor) 大概有三個, 分别是: 

0: Standard Input (STDIN) 

1: Standard Output (STDOUT) 

2: Standard Error Output (STDERR) 

在标準情況下, 這些FD分别跟如下裝置關聯: 

stdin(0): keyboard  鍵盤輸入,并傳回在前端 

stdout(1): monitor  正确傳回值 輸出到前端 

stderr(2): monitor 錯誤傳回值 輸出到前端 

舉例說明吧: 

目前目錄隻有一個檔案 a.txt. 

[[email protected] box]# ls 

a.txt 

[[email protected] box]# ls a.txt b.txt          

ls: b.txt: No such file or directory     由于沒有b.txt這個檔案, 于是傳回錯誤值, 這就是所謂的2輸出 

a.txt     而這個就是所謂的1輸出 

再接着看: 

[[email protected] box]# ls a.txt b.txt  1>file.out 2>file.err 

執行後,沒有任何傳回值. 原因是, 傳回值都重定向到相應的檔案中了,而不再前端顯示 

[[email protected] box]# cat file.out 

a.txt 

[[email protected] box]# cat file.err 

ls: b.txt: No such file or directory 

一般來說, "1>" 通常可以省略成 ">". 

即可以把如上指令寫成: ls a.txt b.txt  >file.out 2>file.err 

有了這些認識才能了解 "1>&2" 和 "2>&1". 

1>&2  正确傳回值傳遞給2輸出通道 &2表示2輸出通道 

如果此處錯寫成 1>2, 就表示把1輸出重定向到檔案2中. 

2>&1 錯誤傳回值傳遞給1輸出通道, 同樣&1表示1輸出通道. 

舉個例子. 

[[email protected] box]# ls a.txt b.txt 1>file.out 2>&1 

[[email protected] box]# cat file.out 

ls: b.txt: No such file or directory 

a.txt 

現在, 正确的輸出和錯誤的輸出都定向到了file.out這個檔案中, 而不顯示在前端. 

補充下, 輸出不隻1和2, 還有其他的類型, 這兩種隻是最常用和最基本的.

本文轉自:http://chenyubo.javaeye.com/blog/321616