‘2>&1‘的庐山真面目

2>&1

如果我们想保存程序的打印信息,为了保存完整的打印信息,通常我们会使用以下命令。那这个该怎么理解呢?

command 2>&1 | tee log
command > log 2>&1

‘2>&1’的意思是将command代码过程中打印的标准输出标准错误代码一并重定向至log文件中。
 

Q:那什么是标准输出和标准错误,什么是重定向,标准输出和标准错误又有什么区别呢?下面一一揭晓:

1. 标准输出和标准错误:
  • 两者默认都是输出到屏幕上
  • 标准输出经过缓冲后才输出,只有缓冲buff满了或者遇到换行符才会输出,可以通过">"重定向至文件
  • 标准错误没有缓冲,立即输出,需要通过"2>"重定向至文件
2. 文件描述符

在linux shell执行命令时,每个进程都和三个打开的文件相联系,并使用文件描述符来引用这些文件。由于文件描述符不容易记忆,shell同时也给出了相应的文件名:

文件文件描述符c++对应实现
标准输入0(缺省是键盘,为0是文件或者其他命令的输出)std::cin
标准输出1(缺省是屏幕,为1时是文件)std::cout
标准错误2(缺省是屏幕,为2时是文件)std::cerr
3. 重定向
signalmeans
>将标准输出重定向至指定文件
>>将标准输出追加到指定文件后面
2>标准错误重定向至指定文件
2 >>标准错误追加到指定文件后面
&无实际意义,表明重定向的是一个文件描述符,而不是一个文件
2>&1将标准错误重定向至标准输出,即将标准错误放进标准输出的缓冲buffer中,一并输出到指定文件

栗子:
下面是标准输出与标准错误的一个小demo

#include<iostream>

int main() {
  std::cout << "hello, this is standard cout_1" << std::endl;
  std::cerr << "hello, this is standard cerr_1" << std::endl;
  std::cout << "hello, this is standard cout_2" << std::endl;
}
  1. 输出至屏幕:./t
屏幕输出:######hello, this is standard cerr      ######hello, this is standard cout      ######hello, this is standard cout
// 注意到cerr输出先于cout,因为cerr是没有缓冲的,      
  1. '>'重定向: ./t > log
屏幕输出:######hello, this is standard cerr      
log文件:######hello, this is standard cout      ######hello, this is standard cout
  1. '2>'重定向: ./t 2> log
屏幕输出:######hello, this is standard cout      ######hello, this is standard cout
log文件:######hello, this is standard cerr  
  1. ‘2>&1’ 重定向: ./t > log 2>&1
屏幕输出:无
log文件(保序):######hello, this is standard cout      ######hello, this is standard cerr      ######hello, this is standard cout

5)'2>&1’重定向: ‘command 2>&1 | tee log’

屏幕输出:######hello, this is standard cout      ######hello, this is standard cerr      ######hello, this is standard cout
log文件(保序):######hello, this is standard cout      ######hello, this is standard cerr      ######hello, this is standard cout
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值