Issue
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:
]
^
Solution
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"
Answered By - Barmar Answer Checked By - Mary Flores (WPSolving Volunteer)