Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script not checking for null correctly

Tags:

bash

jq

I have a bash script:

#! /bin/bash

someId=$(curl -sk -H -X POST -d "fizzbuzz" "https://someapi.example.com/v1/orders/fire" | jq '.someId')

if [ -z "$someId" ]; then
  echo "Order Placement failed; unable to parse someId from the response"
  exit 1
fi

echo "...order $someId placed"

When I run this I get the following output:

...order null placed

So somehow $someId is null but then...shouldn't I be seeing the "Order Placement failed; unable to parse someId from the response" echo instead?

How can I modify the if [ -z "$someId" ]; then conditional to execute if $someId is null?

like image 927
hotmeatballsoup Avatar asked Mar 27 '26 09:03

hotmeatballsoup


1 Answers

Use the --exit-status option, which makes jq have a non-zero exit status if the last output value is false or null.

#! /bin/bash


if ! someId=$(curl -sk -H -X POST -d "fizzbuzz" "https://someapi.example.com/v1/orders/fire" | jq -r --exit-status '.someId'); then
  echo "Order Placement failed; unable to parse someId from the response"
  exit 1
fi

echo "...order $someId placed"
like image 101
chepner Avatar answered Mar 31 '26 04:03

chepner