Bash 脚本未正确检查 null

hot*_*oup 2 bash jq

我有一个 bash 脚本:

#! /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"
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到以下输出:

...order null placed
Run Code Online (Sandbox Code Playgroud)

所以不知怎的$someIdnull但是……我不应该看到"Order Placement failed; unable to parse someId from the response"回声吗?

如何修改条件以在为空时if [ -z "$someId" ]; then执行?$someId

che*_*ner 5

使用该--exit-status选项,如果最后的输出值为或 ,jq则具有非零退出状态。falsenull

#! /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"
Run Code Online (Sandbox Code Playgroud)

  • 应该是“如果!” 一些Id=...`? (3认同)