bash 脚本 – 输出流重定向至错误流(stderr)

在C/C++里,都有各自的方法用于向错误流写数据。如:

  • fprintf(stderr, “Hello World\n”);
  • cerr << “Hello World” << endl;

在bash脚本里,可以用echo “Hello World”向标准输出写入数据,可如何像标准错误流写入数据呢?同样有两种方法:

  • echo “Hello World” >> /dev/stderr
  • echo “Hello World” >&2

测试的方法,以上命令任选其一写入一个脚本,假定命名为test.sh,执行

  • ./test.sh 2> /tmp/test
  • cat /tmp/test

“Hello World”出来了吧?目前我还没发现能用一句命令来进行这个测试的,如果谁有,请别忘了指点一下。

非常感谢小椿和smzz的帮助。

参考链接:Bash的输入输出重定向

About 王永杰

路漫漫其修远兮,吾将上下而求索
This entry was posted in linux应用, 技术为本 and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>