我正在尝试像这样将变量传递给 jq'.Linux.date.$var'
到目前为止,我已经尝试按名称引用它们,这工作正常。但我想用变量来调用它们。
我有这个,它工作正常
exectime=$(date -d now);
cp $check_exec_history $check_exec_history.tmp
jq --arg key1 true --arg key2 "$exectime" --arg name "$name" '.Linux.script_executed.first = $key1 | .Linux.date_executed.first = $key2' $check_exec_history.tmp > $check_exec_history;
rm $check_exec_history.tmp;
我想做到这一点,但不工作:
name=first;
exectime=$(date -d now);
cp $check_exec_history $check_exec_history.tmp
jq --arg key1 true --arg key2 "$exectime" --arg name "$name" ".Linux.script_executed.$name = $key1 | .Linux.date_executed.$name = $key2" $check_exec_history.tmp > $check_exec_history;
rm $check_exec_history.tmp;
我走了这么远:使用这个答案https://stackoverflow.com/q/40027395/9496100但我不确定我在哪里做错了。
name=first;
exectime=$(date -d now);
cp $check_exec_history $check_exec_history.tmp
jq --arg key1 true --arg key2 "$exectime" --arg name "$name" '.Linux.script_executed.name==$name = $key1 | .Linux.date_executed.name==$name = $key2' $check_exec_history.tmp > $check_exec_history; rm $check_exec_history.tmp;
您可以对 jq 中的所有对象使用方括号索引,因此
[$name]
适用于您正在尝试的内容:方括号的使用在手册中没有很好地记录,这使得它看起来你只能使用
.[xyz]
,但只要它不在表达式的开头(也就是说,并且是相同的),它就["x"]
可以在任何地方使用,但是是一个数组构造)。.x
.a.x
.a["x"]
["x"]
请注意上面使用单引号 - 这样 Bash 不会尝试将
$name
和解释$key1
为 shell 变量。你应该为 保留双引号--arg name "$name"
,因为它确实是一个 shell 变量,它应该被引用以使其安全使用。迈克尔荷马有正确的反应。我将发布与 op 的问题相关的目标。
我正在尝试修改通过 REST API curl 调用获得的权限图,
jq
以输出一个 json 文件,我将PUT
使用更新将其发送到服务器。以下是 curl API 查询的输出:如您所见,它是嵌套的。每次创建新权限集和创建数据库时,我都会尝试使用 bash 变量来修改它。例如,我正在尝试修改
groups."1"."2"."native"
“模式”"groups."2"."2".native
和“模式”值。很粗糙,但是关键如下groups.groupPermissionID.DatabaseID.*
为了通过 bash shell 脚本即时修改这个嵌套图,我使用了 Michael Homer 的应用解决方案
[$name]
。就我而言,我必须连续两次这样做。即,[$gID][$dID]
。在以下设置中,变量是常量,但在我的模型中,它们是传递给 bash shell 脚本的命令参数。PUT
它为我的服务器生成了以下更新的 JSON 图:当迈克尔说这很少有记录时,他是正确的。我在手册的任何地方都找不到它。我希望这可以帮助别人。