bash 以错误的方式重定向到同一个文件

问题描述 投票:0回答:0

在 bash 中,我知道

foo 1>a.txt 2>&1
将 stdout 和 stderr 输出到同一个文件。 但是,如果我用
foo 1>a.txt 2>a.txt
替换它,它的行为会很奇怪。

GNU bash,版本 5.1.16(1)-release (x86_64-pc-linux-gnu)

示例代码在这里:

#!/usr/bin/bash

function foo {
  echo stdout1
  echo stdout2
  echo stdout3
  echo stderr1 >&2
  echo stderr2 >&2
  echo stdout4
}

foo 1>a.txt 2>a.txt

那么a.txt的内容就是

stderr1
stderr2
stdout3
stdout4

奇怪的一点是我希望 stdout 根本不会出现,或者, 表现得像

1> a.txt 2>&1
,但事实并非如此。 一个问题是 a.txt 以写入模式打开了两次。 我想知道在这个重定向中发生了什么。

bash io-redirection
© www.soinside.com 2019 - 2024. All rights reserved.