shell中2>&1的含义

在做实验的过程中,经常会看到shell脚本里存在 2>&1 的指令组合,有点懵逼,在此记录一下。

0 | 1 | 2

这三个数字是linux文件描述符。

数字含义
0stdin
1stdout
2stderr

12 都是输出到屏幕设备上。

我们平时使用的:

echo "Hello World" > test.log

等价于:

echo "Hello World" 1> test.log

注意 1> 是连在一块的。如果分开,那么写入文件的就是 Hello World 1

2>&1

将标准错误输出重定向到标准输出。

示例

import sys
sys.stdout.write("this is stdout\n")
sys.stderr.write("this is stderr\n")
python test.py > test.log 2>&1

表示将标准错误输出重定向到标准输出,标准输出重定向到 test.log 文件中。

在程序执行过程中,我们希望输出保存到文件中,如果有错误的信息也希保存到文件中,那么就使用上面的命令。

  • python test.py > test.log 2>1 : 那么标准输出将重定向到 test.log ,而错误将输出到名字为 1 的文件中。这里的 & 可以理解为 1 的引用
  • python test.py > test.log 2 >&1 : 那么标准输出将重定向到 test.log ,而错误将输出到屏幕上
  • python test.py > test.log 2>& 1 : 等价于 python test.py > test.log 2>&1
  • python test.py 1> test.log 2> test.log : 会存在如下两个问题:
    • stdout 会覆盖 stderr
    • test.log 会被打开两次,IO效率低下

2>&1 为什么放在末尾?

python test.py > test.log 2>&1 从左往右来看 stdin 定向到 test.log,然后 stderr 定向到 stdin,等于说 stderr 也输入到了 test.log 中。

如果放在中间:python test.py 2>&1 >test.logstderr 定向到 stdin,但此时 stdin 指向的是屏幕,所以 stderr 会输出到屏幕。执行到 >test.log 的时候,stdin 定向到 test.log。所以 test.log 文件里只有 this is stdout

简写

python test.py > test.log 2>&1

可以简写成:

python test.py >& test.log

参考自

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值