13

I am doing a string comparison between a variable and a constant. The result of the comparison, either true or false, is assigned to another variable.

LABEL=$("${INPUT}" == "flag");

However, I am failing. Any suggestion?

tashuhka
  • 5,028
  • 4
  • 45
  • 64

2 Answers2

17

You can use expr:

INPUT='flag'
LABEL=$(expr "${INPUT}" == "flag")
echo "$LABEL"
1

INPUT='flab'
LABEL=$(expr "${INPUT}" == "flag")
echo "$LABEL"
0
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Is it possible that the evaluation returns `true`/`false` instead of `0`/`1`? – tashuhka Nov 19 '14 at 11:12
  • 4
    No that will require little longer version as this: `[[ "$INPUT" == "flag" ]] && LABEL=true || LABEL=false` – anubhava Nov 19 '14 at 11:13
  • Should it be `LABEL=$(expr "${INPUT}" = "flag")`? The double equals doesn't work for me – denixtry May 22 '19 at 17:08
  • This will return an error, or unexpected results if `$INPUT` (or `"flag"`) contains any `expr` expressions such as `(`, `+`, `substr`, [and others](https://linux.die.net/man/1/expr). – cbr Oct 21 '21 at 07:14
0

This is probably easier and can cover more test cases. For you can get more details about string comparisons and test cases via 'man test'. Here's a pretty basic sample.

if [ "${INPUT}" == "flag" ]; then
   LABEL=${INPUT}
fi

echo ${LABEL}
  • This straight up doesn't work for cases where the comparison is false though. It also defeats the whole point of the question which is to avoid the noobish commonplace if then true else false assignment – Shardj Mar 13 '19 at 09:47