shell 编程之2>&1
NinGoo's blog

shell 编程之2>&1

经常可以在一些脚本,尤其是在crontab调用时发现如下形式的命令调用


/tmp/test.sh > /tmp/test.log 2>&1

前半部分/tmp/test.sh > /tmp/test.log很容易理解,那么后面的2>&1是怎么回事呢?

要解释这个问题,还是得提到文件重定向。我们知道>和<是文件重定向符。那么1和2是什么?在shell中,每个进程都和三个系统文件相关联:标准输入stdin,标准输出stdout和标准错误stderr,三个系统文件的文件描述符分别为0,1和2。所以这里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文件中了。

实际上, > 就相当于 1> 也就是重定向标准输出,不包括标准错误。通过2>&1,就将标准错误重定向到标准输出了,那么再使用>重定向就会将标准输出和标准错误信息一同重定向了。如果只想重定向标准错误到文件中,则可以使用2> file

本文网址:http://www.ningoo.net/html/2007/shell_scripts_stderr_stdout.html

订阅到Google | 收藏到Del.icio.us | 推荐到鲜果

上一篇: 下一篇:
相关文章 随机文章
  • No Related Post

本文Tags:

6 条评论

  • At 2007.10.10 12:34, 木匠 said:

    我在想为啥不用 2>1, 而是 2>&1 …?

    • At 2007.10.10 15:24, NinGoo said:

      2>1的意思是将stderr重定向输出到名字为1的文件中了

      &1是引用stdout的文件句柄,也就是将stderr合并到stdout中去

    • At 2007.10.11 01:23, 木匠 said:

      妙, 这下全搞清楚了.

      • At 2007.10.12 14:07, westlife_xu said:

        这篇文章最有用的就是上面两句

        • At 2007.11.20 01:58, 木匠 said:

          看来还是咱的提问有艺术,嘻嘻.

          • At 2007.11.30 10:31, NinG00 said:

            哈哈,刚刚注意到是 NinGoo写的。。。不错我用上了


            (Required)
            (Required, will not be published)