Home > Software design >  How to use variable command in a if statement
How to use variable command in a if statement

Time:01-13

How to use the output of the variable STATUS in the following if statement?

I don't understand why the following if statement does not work.

$ declare STATUS=$(cat file.txt| grep 'relation": "next' | sed 's/^.*": *//;q' )
$ echo $STATUS
"next",

if test "$STATUS" = "next,"
then
    echo "YES"
fi

Also if possible, how to remove the caracters , and "

I could do something like

  • original command: sed 's/^.*": *//;q'

  • to remove " do this: sed 's/"//;q'

  • to remove , do this: sed 's/,//;q'

But it would be best having only one sed command that does all

CodePudding user response:

You can do all the substitutions in single sed like this:

sed -E 's/^.*": *|[",] //g'

btw both cat and grep are not required, just use sed:

status=$(sed -E '/relation": "next/ s/^.*": *|[",] //g' $FILE_NAME.json)

# check variable
declare -p status

# compare it
if [[ $status = "next" ]]; then
   echo "YES"
fi

CodePudding user response:

Addressing the question of why the current if/test fails ...

To better understand what bash sees we'll turn on debugging (set -x):

$ set -x
$ if test "$STATUS" = "next,"; then echo "YES"; fi
  test '"next",' = next,

From this we see the first issue ... $STATUS includes a set of double quotes within the value of the variable while the other side of the comparison does not.

One idea to make sure the double quotes are included in the content of the right side of the test:

$ if test "$STATUS" = '"next",'; then echo "YES"; fi
  test '"next",' = '"next",'

From this we see the 2nd issue ... comma inside the double quotes on the left, comma outside the double quotes on the right.

Move the comma inside the double quotes:

$ if test "$STATUS" = '"next,"'; then echo "YES"; fi
  test '"next",' = '"next",'
  echo YES
YES

At this point we've got the desired result, ie, YES is printed to stdout.


An alternative approach that strips the double quotes out of the left side of the comparison via parameter substitution:

$ if test "${STATUS//\"/}" = "next,"; then echo "YES"; fi
  test next, = next,
  echo YES
YES

NOTES:

  • ${STATUS//\"/}" says to replace the literal " with nothing (ie, remove them)
  • the double quotes are still contained within the contents of STATUS; we've merely removed them from what bash sees when running the comparison
  • Related