1

Given this script:

#!/bin/bash
COMMAND=$(echo test | jq)
if [[ $COMMAND == *"error"* ]]; then
        echo failed
        else
        echo success
fi

Since the output of $(COMMAND) is the following: parse error: Invalid literal at line 2, column 0, I'd expect to have as output of that script failed, but I'm having success.

How can I parse the error that I got on scripts?

script_jr
  • 15
  • 5

1 Answers1

1

jq prints errors to stderr so you'd have to do this:

COMMAND=$(echo test | jq 2>&1)

But checking if command failed can be done using much easier method in Bash:

#!/usr/bin/env bash

if ! echo test | jq '.'
then
    echo failed
else
    echo success
fi
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
  • ...also better to use `jq <<<"test"` and avoid a subshell just to run `echo` on the left-hand side of the pipeline in the first place. – Charles Duffy Sep 29 '20 at 15:58