这是正确的吗?
existed_design_document=$(curl "Administrator:*******@couchbase:8092/$MY_APP_DB_BUCKET/_design/dev_$environment" | jq '.error ')
echo "$existed_design_document"
if [ "$existed_design_document" == "not_found" ]
then
echo "The document design does not exist"
fi
我在echo中看到了值“not_found”,但仍然没有进入if。知道为什么吗?
答案 0 :(得分:2)
当我尝试这个婴儿的例子时:
$ a=$(echo '{"error": "not_found"}' | jq .error)
我明白了:
$ declare -p a
declare -- a="\"not_found\""
因此引号也在jq
的输出中。所以你需要这个:
if [[ $existed_design_document = "\"not_found\"" ]]
正如@EtanReisner指出的那样(谢谢!):jq
有-r
标志:
With this option, if the filter´s result is a string then it will
be written directly to standard output rather than being formatted
as a JSON string with quotes. This can be useful for making jq fil‐
ters talk to non-JSON-based systems.
所以你甚至应该这样做:
existed_design_document=$(curl "Administrator:*******@couchbase:8092/$MY_APP_DB_BUCKET/_design/dev_$environment" | jq -r .error)
echo "$existed_design_document"
if [[ $existed_design_document = "not_found" ]; then
echo "The document design does not exist"
fi
答案 1 :(得分:0)
一个更可靠的解决方案不受引号的影响,但只查找给定的字符串是基于正则表达式。这将符合您的文字:
if [[ $existed_design_document =~ not_found ]]; then
echo "The document design does not exist"
fi
这将匹配包含not_found的任何内容,因此,它更灵活,但也可以匹配某些UN预期的字符串。这是灵活性和精确度之间的权衡。