Home > Database > Mysql Tutorial > body text

shell 编程之2>&1

WBOY
Release: 2016-06-07 15:20:04
Original
1242 people have browsed it

经常可以在一些脚本,尤其是在crontab调用时发现如下形式的命令调用 /tmp/test.sh /tmp/test.log 21 前半部分/tmp/test.sh /tmp/test.log很容易理解,那么后面的21是怎么回事呢? 要解释这个问题,还是得提到文件重定向。我们知道和是文件重定向符。那么1和2

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

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

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

要解释这个问题,还是得提到文件重定向。我们知道>和&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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!