当前位置: > CentOS > CentOS入门 >

centos重定向命令

时间:2016-09-19 19:35来源:linux.it.net.cn 作者:IT
yw >outfile 2>&1
$ cat outfile 
cat: oyyw: 没有那个文件或目录

$ cat oyyw 2>&1 >outfile
cat: oyyw: 没有那个文件或目录

解惑

搜集了一部分资料以后,解答如下:

顺序是很重要的!命令的执行是自左向右的,因此:  * 对于第一个命令,shell首先读到>outfile(等同于1>outfile),此时标准输出重定向到了文件outfile,然后shell再读到2>&1,此时标准错误输出重定向到了标准输出,也就是重定向到了文件outfile,所以得到的结果是 标准输出和标准错误输出都重定向到了文件outfile中

  • 对于第二个命令,shell首先读到2>&1,此时标准错误输出重定向到了标准输出(可能是控制台),然后shell再读到>outfile(等同于1>outfile),此时标准输出重定向到了文件outfile,得到的结果是 标准错误输出输出到了控制台,标准输出输出到文件outfile中

以下这个例子,应该可以很好解答上面的疑问了:

$ cat learn_redirect.sh 
#!/bin/bash

foo() {
    echo "This is stdout";        # 输出是标准输出
    echo "This is stderr" 1>&2;   # 输出是标准错误输出
}

foo >errlog 2>&1 >outfile
[pms@jq-hadoop ~/workspace/ouyangyewei/learn_linux] eth0 = xxx
$ sh learn_redirect.sh 
[pms@jq-hadoop ~/workspace/ouyangyewei/learn_linux] eth0 = xxx
$ cat outfile 
This is stdout
[pms@jq-hadoop ~/workspace/ouyangyewei/learn_linux] eth0 = xxx
$ cat errlog 
This is stderr

解释如下

foo >errlog 2>&1 >outfile 这一句命令,shell执行顺序是从左向右。首先shell读到>errlog,此时标准输出重定向到了文件errlog,然后shell读到2>&1,此时标准错误输出重定向到了标准输出(等同于标准错误输出重定向到了文件errlog),然后shell读到>outfile,此时标准输出重定向到文件outfile,因此,得到的结果是 标准错误输出输出到文件errlog中,标准输出输出到了文件outfile中

参考资料

http://www.gnu.org/software/bash/manual/bash.html#Redirections http://mywiki.wooledge.org/BashFAQ/055  http://docstore.mik.ua/orelly/unix/upt/ch45_21.htm http://docstore.mik.ua/orelly/unix/upt/ch08_13.htm

(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容