Linux輸出重定向

標準輸入輸出

輸出重定向

>  代表以覆蓋的方式將命令的正確輸出輸出到指定的文件或設備當中。 
>> 代表以追加方式輸出。

 正確輸出和錯誤輸出同時保存

[kathy@localhost testDir]$ ll
total 8
-rw-rw-r--. 1 kathy kathy 12 Jul 31 10:15 test
-rw-rw----. 1 root  root  12 Jul 31 10:15 test2
[kathy@localhost testDir]$ cat test test2
output test
cat: test2: Permission denied

現有兩個文件,用戶讀取test,屬於正確標準輸出;用戶無權限讀取test2,屬於標準錯誤輸出。

1、 >

[kathy@localhost testDir]$ cat test test2 > log
cat: test2: Permission denied
[kathy@localhost testDir]$ cat log 
output test

單獨的>,把標準輸出寫入到log文件,而錯誤輸出依舊顯示在屏幕。 此時默認情況是沒有改變2=stderr的輸出方式,還是屏幕,所以,如果有錯誤信息,還是可以在屏幕上看到的。

2、1>

1>,只把標準輸出寫入到log文件,而錯誤輸出依舊顯示在屏幕。

[kathy@localhost testDir]$ cat test test2 1> log
cat: test2: Permission denied
[kathy@localhost testDir]$ cat log
output test

相應地,由於2=stderr沒有變,還是屏幕,所以,那些命令執行時候輸出的錯誤信息,還是會輸出到屏幕上。

3、2>

2>,只把錯誤信息寫入到log文件,而標準輸出依舊顯示在屏幕。

[kathy@localhost testDir]$ cat test test2 2> log
output test
[kathy@localhost testDir]$ cat log 
cat: test2: Permission denied

由於1=stdout沒有變,還是屏幕,所以,那些命令執行時候輸出的正常信息,還是會輸出到屏幕上,你還是可以在屏幕上看到的。

4、&>、>&

&>,將標準輸出和錯誤信息同時寫入log文件,屏幕上沒有任何顯示。

[kathy@localhost testDir]$ cat test test2 &> log
[kathy@localhost testDir]$ cat log 
output test
cat: test2: Permission denied
[kathy@localhost testDir]$ cat test test2 >& log
[kathy@localhost testDir]$ cat log
output test
cat: test2: Permission denied

同時改變了1=stdout和2=stderr,要寫入文件,所以,執行命令後的所有輸出信息,都不會顯示在屏幕上。

5、2>&1

所有的信息都輸出到同一個文件中。

[kathy@localhost testDir]$ cat test test2 >log 2>&1
[kathy@localhost testDir]$ cat log 
output test
cat: test2: Permission denied

其中的2>&1表示錯誤信息輸出到&1中,而&1,指的是前面的那個文件:log 。

注意:此處的順序不能更改,否則達不到想要的效果,此時先將標準輸出重定向到log,然後將標準錯誤重定向到標準輸出,由於標準輸出已經重定向到了log,因此標準錯誤也會重定向到log,於是一切靜悄悄。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章