bash shell:重定向標準錯誤輸出

如何重定向標準錯誤輸出到標準輸出?如何把標準錯誤輸出輸出到一個文件?

Bash提供了I/O重定向工具,有3個缺省的文件(標準輸出流):
stdin - 用來獲取輸入,好比鍵盤、文件重定向
stdout - 輸出數據,缺省打印到屏幕
stderr - 輸出錯誤信息,缺省打印到屏幕bash

理解I/O(標準輸入/輸出流):
工具






句柄 名字 描述
0 stdin 標準輸入
1 stdout 標準輸出
2 stderr 標準錯誤輸出

重定向標準錯誤輸出到文件, 標準輸出仍是輸出到屏幕

[root@ns_10.2.1.242 test]$ cat1  2> error.log 
[root@ns_10.2.1.242 test]$ cat error.log 
-bash: cat1: command not found
[root@ns_10.2.1.242 test]$ echo 1 2> error.log 
1
[root@ns_10.2.1.242 test]$ cat error.log 
[root@ns_10.2.1.242 test]$

重定向標準錯誤輸出和標準輸出到文件

$ command-name &>file
or
$ command > file-name 2>&1

[root@ns_10.2.1.242 test]$ echo 1 &>error.log 
[root@ns_10.2.1.242 test]$ cat error.log 
1
[root@ns_10.2.1.242 test]$ cat1 &>error.log 
[root@ns_10.2.1.242 test]$ cat error.log    
-bash: cat1: command not found

重定向標準輸出到標準輸入

使用下面的命令:code

$ command-name 2>&1

#注意下面兩個例子的區別
# 第一個命令沒法更改標準錯誤輸出的內容, 第二個命令由於把stderr 重定向到stdin, 因此 cat1 被替換成了 test
[root@ns_10.2.1.242 test]$ cat1 |sed 's/cat1/test/'
-bash: cat1: command not found
[root@ns_10.2.1.242 test]$ cat1 2>&1|sed 's/cat1/test/' 
-bash: test: command not found
相關文章
相關標籤/搜索