我想使用jq
将包依赖项添加到package.json
文件by bash
脚本中.
Add new element to existing JSON array with 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
命令?