You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本执行dotnet test时如何用grep匹配结果同时隐藏stderr输出

问题解决方法

你当前脚本的问题本质是shell管道默认仅传递前序命令的标准输出(stdout,文件描述符为1),dotnet test输出到标准错误(stderr,文件描述符为2)的内容不会进入管道,会默认直接打印到终端。
要隐藏stderr的冗余输出,同时不影响grep对stdout内容的失败匹配,直接对dotnet命令的stderr做重定向丢弃即可。

核心修改

把原来捕获测试输出的那行命令,加上2>/dev/null重定向规则即可,修改后完整逻辑如下:

# Run the tests.
DOTNET_TEST_OUTPUT=$(dotnet test --no-build --no-restore Restify.sln 2>/dev/null | grep "Failed!")

# If any test failed, inform the user and terminate the script.
if ! [ -z "$DOTNET_TEST_OUTPUT" ]
then
    echo -e "        \033[0;31m[ERROR]: One or more unit tests did fail.\033[0m"
    echo -e "                 \033[0;31mFor more information, execute \`dotnet test Restify.sln\` in the \`./app\` folder.\033[0m"

    # Terminate the script (with an exit code different from `0`) to notify git that this git HOOK has failed.
    # This results in the abort of the commit.
    exit 1
fi

规则说明

  • 2>/dev/null:代表将文件描述符2(即stderr)的所有输出,重定向写入系统特殊空设备/dev/null,所有写入该设备的内容会被直接丢弃,不会展示在终端上。
  • 该修改不会影响dotnet test的正常标准输出内容,所有stdout内容依旧会通过管道传递给grep做关键词匹配,原有的测试失败检测逻辑完全不受影响。

可选补充

如果你的脚本开启了set -e(遇到命令非0退出就自动终止脚本)模式,grep在没有匹配到"Failed!"内容时会返回非0退出码,可能导致脚本意外中断,可以在grep后补|| true规避该问题:

DOTNET_TEST_OUTPUT=$(dotnet test --no-build --no-restore Restify.sln 2>/dev/null | grep "Failed!" || true)

如果你不希望完全丢弃stderr内容,只是不想它默认打印到终端,也可以把stderr重定向到单独的临时文件,后续真的需要排查异常时再读取对应文件内容即可。


内容的提问来源于stack exchange,提问作者Complexity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 05:51:16