I am creating a simple bash script. I have this curl request, and I only want to send objects_count
in my raw data body if it is non empty.
I know that this line of code works:
'[ ! -z "$objects_count" ] && echo "not empty"'
However when I implement it in my curl request, I get an error
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:
]
^
CodePudding user response:
Bash doesn't have a conditional operator that can be used in expressions. Use a simple if
statement to set a variable to the data you want to send.
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"
CodePudding user response:
You cannot use expressions like that in the middle of an expression. If you really want an expression you need a subshell, and inside the subshell echo
the string you want:
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)'
}'
However, there's a trick using parameter substitution where you can expand a string only of a variable isn't null (or unset):
echo ${objects_count: non empty}
Then you don't need an expression:
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}'
}'
I don't see why you would need to selectively output this element though, in JSON you can typically just do "object_counts": null
or something like that.
BTW, instead of doing [ ! -z "$foo" ]
you can just do [ -n $foo ]
.