Saturday, March 08, 2008

shell 编程之2>&1_一树寒梅白玉条,迥临村路傍溪桥

shell 编程之2>&1_一树寒梅白玉条,迥临村路傍溪桥: "下面通过一个例子来展示2>&1有什么作用:
$ cat test.sh
t
date

test.sh中包含两个命令,其中t是一个不存在的命令,执行会报错,默认情况下,错误会输出到stderr。date则能正确执行,并且输出时间信息,默认输出到stdout
./test.sh > test1.log
./test.sh: line 1: t: command not found

$ cat test1.log
Tue Oct 9 20:51:50 CST 2007

可以看到,date的执行结果被重定向到log文件中了,而t无法执行的错误则只打印在屏幕上。
$ ./test.sh > test2.log 2>&1

$ cat test2.log
./test.sh: line 1: t: command not found
Tue Oct 9 20:53:44 CST 2007

这次,stderr和stdout的内容都被重定向到log文件中了。"