zoukankan      html  css  js  c++  java
  • 一个常考重定向问题

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

    ./a.out > outfile 2>&1

    ./a.out 2>&1 > outfile

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

    int main(){
           printf("output to stdio\n");
           fprintf(stderr,"output to stderr\n");
           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
  • 相关阅读:
    自定义input file样式
    input text 不显示输入的历史记录
    白话 P-value
    R博客
    安装NXNET
    形象的解释神经网络激活函数的作用是什么?
    嵌入式选择与L1正则化
    “梯度下降法”理解
    控制台乱码
    R语言快捷键
  • 原文地址:https://www.cnblogs.com/zhaoyl/p/2733418.html
Copyright © 2011-2022 走看看