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

Shell脚本中如何基于curl返回的JSON错误信息实现日志记录?

解决方案:用jq解析JSON而非grep处理结构化数据

直接用grep匹配"errors"字符串不可靠——即便errors是空数组(比如"errors": []),grep也会触发匹配,但此时并没有实际错误。要准确判断errors数组是否包含带errorMessage的元素并提取内容,应该用专门的JSON解析工具jq(大多数Linux发行版可通过包管理器安装,比如apt install jq或yum install jq)。

改进后的脚本

# 执行curl命令并捕获自身执行状态(可选,覆盖网络/请求层面的失败)
curl --cacert ds***ds*DS*ghgjhg** > /data/result.out
curl_exit_code=$?

# 先判断curl本身是否执行失败(比如证书错误、网络不通)
if [ $curl_exit_code -ne 0 ]; then
    echo "curl command failed: 网络或请求异常"
    exit 1
fi

# 用jq解析JSON,提取errorMessage(无错误则返回空)
error_msg=$(jq -r '.errors[]?.errorMessage // empty' /data/result.out)

if [ -n "$error_msg" ]; then
    echo "curl command failed.. $error_msg"
else
    echo "curl command successfully executed"
fi

关键逻辑说明

  • jq -r '.errors[]?.errorMessage // empty':
    • .errors[]?:遍历errors数组的每个元素,?避免数组为空时抛出错误
    • .errorMessage:提取元素中的错误信息字段
    • // empty:如果无该字段或数组为空,返回空字符串
  • [ -n "$error_msg" ]:判断提取到的错误信息是否非空,非空则说明存在业务错误

无jq环境的临时方案(不推荐)

如果环境限制无法安装jq,可尝试用grep+awk做近似处理,但该方法依赖JSON的排版格式(比如换行、空格),兼容性差:

# 检查errors数组内是否存在errorMessage字段
if grep -A5 '"errors"' /data/result.out | grep -q '"errorMessage"'; then
    error_msg=$(grep -A2 '"errorMessage"' /data/result.out | awk -F'"' '{print $4}')
    echo "curl command failed.. $error_msg"
else
    echo "curl command successfully executed"
fi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:48:14