我想使用
package.json
通过 bash
脚本将包依赖项添加到 jq
文件。
这是包含 5 个步骤的测试脚本:
#!/bin/bash
add_element_with_jq() {
# step 1: Add a new root element "{}" first
echo "============= step 1 ================"
echo "{}" > "package.json"
# step 2: Add a "dependencies" sub element to the root element "{}"
echo "============= step 2 ================"
# step 3: Add a "foo" package with version "1.1.1" to the "dependencies"
echo "============= step 3 ================"
jq '. += dependencies {
"foo": "1.1.1"
}' "package.json"
echo "=========== step 3 output =================="
cat "package.json"
# step 4: Add a "bar" package with version "2.2.2" to the "dependencies"
echo "============= step 4 ================"
jq '.dependencies +=
"bar": "2.2.2"
' "package.json"
# step 5: If the "foo" package already existed, then update to the latest version. Otherwise, add the "foo" package to the dependencies.
echo "============= step 5 ================"
jq '.dependencies +=
"foo": "3.3.3"
' "package.json"
echo "=========== final output =================="
cat "package.json"
}
add_element_with_jq
这是错误:
============= step 1 ================
============= step 2 ================
============= step 3 ================
jq: error: syntax error, unexpected '{', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
. += dependencies {
jq: 1 compile error
=========== step 3 output ==================
{}
============= step 4 ================
jq: error: syntax error, unexpected ':', expecting $end (Unix shell quoting issues?) at <top-level>, line 2:
"bar": "2.2.2"
jq: 1 compile error
============= step 5 ================
jq: error: syntax error, unexpected ':', expecting $end (Unix shell quoting issues?) at <top-level>, line 2:
"foo": "3.3.3"
jq: 1 compile error
=========== final output ==================
{}
这是预期的输出:
=========== step 3 output ==================
{
"dependencies": {
"foo": "1.1.1"
}
}
=========== final output ==================
{
"dependencies": {
"foo": "3.3.3",
"bar": "2.2.2"
}
}
我的
bash
函数出了什么问题,如何修复 jq
命令?
使用的语法(
. += dependencies
)似乎不正确。
要在
dependencies
中添加或编辑条目,请使用以下语法:
jq '.dependencies["foo"]="1.1.1"' "package.json"
这将输出编辑的内容。由于我们无法通过管道返回到文件(在执行
jq
时打开文件以供读取),因此我们必须将其通过管道传输到新文件并重命名(为此使用 mv
命令)。
jq '.dependencies["foo"]="1.1.1"' "package.json" > package.json.new \
&& mv package.json.new package.json