1. 程式人生 > >> outfile 2>&1 與 2>&1 > outfile

> outfile 2>&1 與 2>&1 > outfile

這篇文章來簡單地說明一下這兩種寫法的區別

首先2>&1的意思是將描述符2重定向至描述符1

現在我們在/test目錄下有一個檔案test,內容為test!!!
我們執行如下兩條命令

cat /test/test > outfile 2>&1
cat /test/test 2>&1 > outfile

兩條命令的輸出均被重定向到了outfile檔案中

但是如果我們把test替換成一個不存在的檔案nofile時,這兩條命令的執行結果就不一樣了

cat /test/test > outfile 2>&1,這條命令沒有任何顯式輸出,因為shell

從左往右執行指令,所以首先輸出被重定向到outfile檔案中,然後標準錯誤被定向到標準輸出,也就是說,標準出錯被重定向到outfile

我們檢視outfile檔案的內容:

[email protected]:/test# cat outfile
cat: /test/nofile: No such file or directory

錯誤資訊被輸出到了nofile

現在執行cat /test/nofile 2>&1 > outfile,結果是錯誤資訊被輸出到了螢幕,這是因為標準出錯被重定向到標準輸出,然後標準輸出才被定向到outfile檔案,因此我們就在螢幕上看到了出錯資訊,而且outfile

中是沒有任何內容的