4

I am trying to parse my curl output with JQ and check the exit code, so when my curl output is empty, JQ return 0 exit code.

For example:

$ echo "" | jq '.key'
$ echo $?
0

How to make this return 1 or some non-zero value?

peak
  • 105,803
  • 17
  • 152
  • 177
James Sapam
  • 16,036
  • 12
  • 50
  • 73

2 Answers2

6

You should use input with -n/--null-input on the command line. This way JQ will fail if its input is empty.

$ echo | jq -n 'input.key'
jq: error (at <stdin>:1): break
$ echo $?
5
$ jq -n '{key: 1}' | jq -n 'input.key'
1
$ echo $?
0
oguz ismail
  • 1
  • 16
  • 47
  • 69
3

If you want to specify the return code when the input is empty, you could use halt_error/1, like so:

$ echo "" | jq -n 'try input.key catch halt_error(9)' 2> /dev/null
$ echo $?
9
peak
  • 105,803
  • 17
  • 152
  • 177