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. 重定向
signal | means |
---|---|
> | 将标准输出重定向至指定文件 |
>> | 将标准输出追加到指定文件后面 |
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;
}
- 输出至屏幕:./t
屏幕输出:######hello, this is standard cerr ######hello, this is standard cout ######hello, this is standard cout
// 注意到cerr输出先于cout,因为cerr是没有缓冲的,
- '>'重定向: ./t > log
屏幕输出:######hello, this is standard cerr
log文件:######hello, this is standard cout ######hello, this is standard cout
- '2>'重定向: ./t 2> log
屏幕输出:######hello, this is standard cout ######hello, this is standard cout
log文件:######hello, this is standard cerr
- ‘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