您的位置:首页 > 运维架构 > Shell

bash shell:重定向标准错误输出

2015-01-24 23:29 260 查看

如何重定向标准错误输出到标准输出?如何把标准错误输出输出到一个文件?

Bash提供了I/O重定向工具,有3个缺省的文件(标准输出流):

stdin - 用来获取输入,比如键盘、文件重定向

stdout - 输出数据,缺省打印到屏幕

stderr - 输出错误信息,缺省打印到屏幕

理解I/O(标准输入/输出流):

句柄 名字 描述
0stdin标准输入
1stdout标准输出
2stderr标准错误输出

重定向标准错误输出到文件, 标准输出还是输出到屏幕

[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

重定向标准输出到标准输入

使用下面的命令:

$ 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: