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

Bash脚本中无法捕获docker pull输出进行grep匹配的问题

问题:Docker拉取镜像脚本未按预期匹配错误信息

执行以下脚本时未达到预期效果:

if docker pull docker.pkg.github.com/private-repo/centos7 | grep -q 'Error response from daemon: unauthorized'; then
  echo "matched"
else 
  echo "unmatched"
fi

实际输出:

Error response from daemon: unauthorized
unmatched

预期输出:

matched

已尝试操作

  • 将docker pull命令替换为echo "Error response from daemon: unauthorized"时,能得到预期的matched输出,说明docker pull的输出未被grep捕获。
  • 另一种尝试(结果相同):
docker pull docker.pkg.github.com/private-repo/centos7 | grep 'Error response from daemon: unauthorized' &> /dev/null
if [ $? == 0 ]; then
   echo "matched"
else
   echo "unmatched"
fi

解决方案

问题根源在于docker pull的错误信息输出到标准错误流(stderr),而管道|默认只捕获标准输出流(stdout),因此需要将stderr重定向到stdout,让grep能捕获到错误内容。

修正后的脚本:

docker pull docker.pkg.github.com/private-repo/centos7 2>&1 | grep 'Error response from daemon: unauthorized' &> /dev/null
if [ $? == 0 ]; then
   echo "matched"
else
   echo "unmatched"
fi

执行后输出:

matched

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:10:16