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

如何在Bash脚本中读取JSON文件值并作为函数输入?

Bash中从JSON提取值并传入函数的问题与解决方法

问题场景

你有如下格式的config.json文件:

[{
  "gain": "90",
  "exposure": "850",
  "whitebalanceR": "120",
  "whitebalanceG": "185",
  "whitebalanceB": "100",
  "Snap": "True"
}
]

你用grep命令逐个提取字段值,能在终端输出正确结果,但将这些值作为参数传入someFunc时执行失败:

# 提取值的grep命令
grep -o '"gain": "[^"]*' config.json | grep -o '[^"]*$'
grep -o '"exposure": "[^"]*' config.json | grep -o '[^"]*$'
grep -o '"whitebalanceR": "[^"]*' config.json | grep -o '[^"]*$'
grep -o '"whitebalanceG": "[^"]*' config.json | grep -o '[^"]*$'
grep -o '"whitebalanceB": "[^"]*' config.json | grep -o '[^"]*$'

# 调用函数的失败命令
./someFunc -w '${whitebalanceR} ${whitebalanceG} ${whitebalanceG}' -ax6 -s ${exposure} -g ${gain} -i 1 -o -a -6

错误原因

  1. 未将提取结果赋值给变量:你只执行了grep命令输出值,但没有把输出结果保存到gain、exposure等bash变量中,直接使用${gain}时,这些变量是空值。
  2. 单引号导致变量不解析:'${whitebalanceR}...'中的单引号会让bash把内容当作字面量字符串,不会解析变量为对应的值。
  3. 参数拼写错误:-w参数里重复写了${whitebalanceG},应该是${whitebalanceB}。

正确解决方法

方法1:修复grep提取与变量赋值

先将grep的输出结果赋值给对应变量,再正确引用变量调用函数:

# 将提取结果赋值给变量
gain=$(grep -o '"gain": "[^"]*' config.json | grep -o '[^"]*$')
exposure=$(grep -o '"exposure": "[^"]*' config.json | grep -o '[^"]*$')
whitebalanceR=$(grep -o '"whitebalanceR": "[^"]*' config.json | grep -o '[^"]*$')
whitebalanceG=$(grep -o '"whitebalanceG": "[^"]*' config.json | grep -o '[^"]*$')
whitebalanceB=$(grep -o '"whitebalanceB": "[^"]*' config.json | grep -o '[^"]*$')

# 调用函数,用双引号包裹变量避免特殊字符问题,修正参数拼写
./someFunc -w "$whitebalanceR $whitebalanceG $whitebalanceB" -ax6 -s "$exposure" -g "$gain" -i 1 -o -a -6

方法2:用jq解析JSON(更可靠)

grep处理JSON不够鲁棒(比如JSON格式调整换行、空格就会失效),推荐用专门的JSON处理工具jq(需先安装,如apt install jq或brew install jq):

# 用jq提取数组第一个元素的对应字段值
gain=$(jq -r '.[0].gain' config.json)
exposure=$(jq -r '.[0].exposure' config.json)
whitebalanceR=$(jq -r '.[0].whitebalanceR' config.json)
whitebalanceG=$(jq -r '.[0].whitebalanceG' config.json)
whitebalanceB=$(jq -r '.[0].whitebalanceB' config.json)

# 调用函数
./someFunc -w "$whitebalanceR $whitebalanceG $whitebalanceB" -ax6 -s "$exposure" -g "$gain" -i 1 -o -a -6
  • -r参数:让jq输出不带引号的原始字符串
  • .[0]:表示取JSON数组的第一个元素
  • .gain:表示取该元素下的gain字段值

关键要点

  • 必须将命令输出赋值给变量,才能在后续命令中引用
  • 变量引用时用双引号包裹,防止值包含空格或特殊字符被bash拆分
  • 处理JSON优先使用专用工具,避免用grep这类文本匹配工具带来的兼容性问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:09:33