zoukankan      html  css  js  c++  java
  • 【转】./a.out 2>&1 > outfile

    原文网址:http://www.cnblogs.com/zhaoyl/archive/2012/10/22/2733418.html

    APUE 3.5关于重定向有个容易迷惑人的问题:

    ./a.out > outfile 2>&1

    ./a.out 2>&1 > outfile

    问两者区别。自己试了下,
      

    复制代码
    int main(){
           printf("output to stdio
    ");
           fprintf(stderr,"output to stderr
    ");
           return 1;
    }
    
    // 结果如下:
    $ ./a.out > outfile 2>&1
    $ cat outfile
    output to stderr
    output to stdin
    $ ./a.out 2>&1 > outfile
    output to stderr
    复制代码

      
      原因是:
      由于bash从左往右处理,在./a.out > outfile的时候,将a.out的fd 1定向到了outfile文件的fd上,然后才遇到2>&1,这时再将a.out的文件描述符2定向到文件描述符1上,这样stderr和stdout,就都到outfile上了。
      
      而下面一个则不然,先遇到2>&1,这时将a.out的文件描述符2定向到文件描述符1上,1是终端。再遇到 > outfile,这时将a.out的文件描述符1重定向到outfile这个文件。结果是,标准错误输出到了屏幕,而标准输出定向到了outfile!

      也可以写shell脚本测试一下:

      

    复制代码
    #!/bin/bash
    
    touch output
    
    test () {
        echo "before error.."
        someerror       #错误,变量或命令未定义
        echo "after error ..."
    }
    
    test  2>&1 >output
    复制代码
  • 相关阅读:
    Codevs 4633 [Mz]树链剖分练习
    Codevs 2460 == BZOJ 1036 树的统计
    洛谷 P1038 神经网络
    POJ 1062 昂贵的聘礼
    POJ 1459 Power Network
    POJ 1149 PIGS
    Codevs 1993 草地排水
    指针与引用
    江哥的DP题(G)
    江哥的DP题(F)
  • 原文地址:https://www.cnblogs.com/wi100sh/p/4280410.html
Copyright © 2011-2022 走看看