我运行一个简单的脚本
#!/bin/bash
git fetch --all 2> stderr.txt
echo "Errorcode $?"
cat -n stderr.txt
echo Sleeping
sleep 1
cat -n stderr.txt
奇怪的是输出
Fetching origin
Errorcode 1
1 fatal: Couldn't find remote ref HEAD
2 error: Could not fetch origin
Sleeping
1 fatal: Couldn't find remote ref HEAD
2 error: Could not fetch origin
3 fatal: The remote end hung up unexpectedly
我怎样才能刷新输出并仍然能够访问错误代码?
我用 stdbuf -o0 -e0
试过了,但没有成功。
刷新与 tee
一起工作,但随后错误代码丢失。
git fetch --all 2>&1 |发球台 stderr.txt >/dev/null
备注:
- 这种情况下的错误是预期的。
- 没有重定向 stderr 也会出现此问题。
- 我使用了 git version 2.11.0
。
最佳答案
问题是在内部,Git fork 了一个单独的进程来进行抓取。那个单独的进程已经告诉父 Git 获取不能成功,在那个单独的进程完成写入它的 stderr 之前,父 Git 退出得太早。
您不能在不修改 Git 源的情况下修复此问题(这是免费提供的,因此您可以修复它,这并不简单)。不过,您可以解决它,例如:
if ! git fetch --all 2> stderr.txt; then
failure=$?
sleep 0.5 # or however long you think is appropriate
... do something with stderr.txt
... use the saved failure code in $? ...
else
# the git fetch worked; $? is 0; no need to sleep
...
fi
管道技巧也很有用,但您需要一个具有类似 bash 的 $PIPESTATUS
数组功能的 shell。请注意,管道技巧之所以有效,是因为 tee
等待管道的所有编写器,并通过运行:
any-command-here 2>&1 | tee ...
您让 shell 等待 tee
,它不仅在等待命令本身,而且还在等待命令生成的任何可以写入 tee
的内容。
关于bash - git退出后的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48776591/