0

I have simple below script

#!/bin/bash

RESPONSE=`jq '.errorCode' /data/logs/errorLog.log`
echo $RESPONSE
if [[ "$RESPONSE" = "INVALID_API_CREDENTIALS" ]]
then
        echo "Registration unsuccessful..."
else
        echo "Registration successful..."
fi

Output

root@ubuntu-test:/data/logs# ./test.sh
"INVALID_API_CREDENTIALS"
Registration successful...
root@gubuntu-test:/data/logs#

Why else block is executing here?

Ganesh Shinde
  • 65
  • 2
  • 7
  • 5
    In your variable, the double-quotes are *part of* the string, but in the string you're comparing it to the double-quotes are *around* the string. Try `if [[ "$RESPONSE" = '"INVALID_API_CREDENTIALS"' ]]` (here, the single-quotes are around the string, making the double-quotes part of the string). Also, `echo $variable` can be misleading for several reasons; see ["I just assigned a variable, but `echo $variable` shows something else"](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else). – Gordon Davisson Jan 06 '23 at 08:22
  • You are using the Bash string comparison operator in a wrong way. It is a double equal sign `==` rather than a single one `=`. – Martin Tovmassian Jan 06 '23 at 08:25
  • 4
    @MartinTovmassian No. In bash, `=` and `==` are equivalent inside `[[…]]` – M. Nejat Aydin Jan 06 '23 at 08:29
  • 1
    And in fact, the POSIX-compatible comparison operator is a single `=` – tripleee Jan 06 '23 at 10:21
  • Side-note, specifying `set -x` below the `#!` script header is very useful to debug these type of issues. – Zlemini Jan 06 '23 at 10:46

1 Answers1

0

Guess it's clear what went wrong from Gordon Davisson comment. Just want to add that jq -r ... also could fix this. And I'd suggest to use bash regex =~ instead of = it could save some space:

if [[ $RESPONSE =~ INVALID ]]
then
        echo "Registration unsuccessful..."
else
        echo "Registration successful..."
fi

It could also be case insensitive with shopt -s nocasematch

Ivan
  • 6,188
  • 1
  • 16
  • 23