我正在創建一個簡單的 bash 腳本。objects_count我有這個 curl 請求,如果我的原始資料正文不為空,我只想發送它。
我知道這行代碼有效:
'[ ! -z "$objects_count" ] && echo "not empty"'
但是,當我在 curl 請求中實作它時,出現錯誤
objects='[]'
objects_count=''
curl --location --request POST 'http://0.0.0.0:5000' \
--header 'Content-Type: application/json' \
--data-raw '{
"objects":'$objects',
'[ ! -z "$objects_count" ] && "objects_count":$objects_count'
}'
curl: (3) URL using bad/illegal format or missing URL
curl: (3) unmatched close brace/bracket in URL position 1:
]
^
uj5u.com熱心網友回復:
Bash 沒有可用于運算式的條件運算子。使用簡單的if陳述句將變數設定為要發送的資料。
if [ -z "$objects_count" ]
then
data='{"objects":'$objects'}'
else
data='{"objects":'$objects', "objects_count":'$objects_count'}'
fi
curl --location --request POST 'http://0.0.0.0:5000' \
--header 'Content-Type: application/json' \
--data-raw "$data"
uj5u.com熱心網友回復:
不能在運算式中間使用這樣的運算式。如果你真的想要一個運算式,你需要一個子shell,在子shellecho中你想要的字串:
curl --location --request POST 'http://0.0.0.0:5000' \
--header 'Content-Type: application/json' \
--data-raw '{
"objects":'$objects',
'$([ ! -z "$objects_count" ] && echo '"objects_count":'$objects_count)'
}'
但是,使用引數替換有一個技巧,您可以僅擴展字串的變數不為空(或未設定):
echo ${objects_count: non empty}
那么你不需要運算式:
curl --location --request POST 'http://0.0.0.0:5000' \
--header 'Content-Type: application/json' \
--data-raw '{
"objects":'$objects',
'${objects_count: '"objects_count":'$objects_count}'
}'
我不明白為什么你需要有選擇地輸出這個元素,但在 JSON 中你通常可以做"object_counts": null或類似的事情。
順便說一句,[ ! -z "$foo" ]你可以做而不是做[ -n $foo ].
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/505192.html
上一篇:使用cURL的多行GET請求
