【转】.a.out 2>&1 > outfile

it2022-05-08  9

原文网址: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\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

转载于:https://www.cnblogs.com/wi100sh/p/4280410.html

相关资源:数据结构—成绩单生成器

最新回复(0)