bash 中 stdout 和 stderr 之间的顺序不匹配
Order mismatch between stdout and stderr in bash
我正在交互式 shell 中执行 bash 命令
./somescript.sh
输出为
OS platform is: linux2
killall agent
agent: no process killed
其中第三行来自 stderr。
但是当我在 subshell as
中执行
var=$('./somescript.sh' 2>&1)
agent: no process killed
OS platform is: linux2
killall agent
为什么 agent: no process killed 现在在第一行打印?
我怎样才能使两者保持一致?
编辑:
然而,当我这样做时,
var=$('./somescript.sh' 1>&2)
我可以看到它在 bash 调试模式下以正确的顺序给出输出。但它没有存储在变量 var 中。
Why did the agent: no process killed is printing in the first line now?
我想那是因为 stdout 是缓冲的,而 stderr 不是(或不是那么多)。因此,stderr get 在 agent: no process killed
行流式传输后刷新,而 stdout
在脚本 ./somescript.sh
存在后刷新。所以第一个出现在屏幕上的是第一个刷新的流 - 即。标准错误。虽然 运行 在控制台中,stderr 和 stdout 都设置为行缓冲,但我猜 bash 将 stdout 设置为完全缓冲的 int 命令替换。
How can I make it consistent to align both of them?
您可以尝试在命令替换中设置行缓冲。 var=$(stdbuf -oL -eL ./somescript.sh 2>&1)
我正在交互式 shell 中执行 bash 命令
./somescript.sh
输出为
OS platform is: linux2
killall agent
agent: no process killed
其中第三行来自 stderr。
但是当我在 subshell as
中执行var=$('./somescript.sh' 2>&1)
agent: no process killed
OS platform is: linux2
killall agent
为什么 agent: no process killed 现在在第一行打印? 我怎样才能使两者保持一致?
编辑:
然而,当我这样做时,
var=$('./somescript.sh' 1>&2)
我可以看到它在 bash 调试模式下以正确的顺序给出输出。但它没有存储在变量 var 中。
Why did the agent: no process killed is printing in the first line now?
我想那是因为 stdout 是缓冲的,而 stderr 不是(或不是那么多)。因此,stderr get 在 agent: no process killed
行流式传输后刷新,而 stdout
在脚本 ./somescript.sh
存在后刷新。所以第一个出现在屏幕上的是第一个刷新的流 - 即。标准错误。虽然 运行 在控制台中,stderr 和 stdout 都设置为行缓冲,但我猜 bash 将 stdout 设置为完全缓冲的 int 命令替换。
How can I make it consistent to align both of them?
您可以尝试在命令替换中设置行缓冲。 var=$(stdbuf -oL -eL ./somescript.sh 2>&1)