In bash, how to make a comparison and assign to a variable

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

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

However, I fail. Any suggestion?

+7
bash string-comparison
source share
2 answers

You can use expr :

 INPUT='flag' LABEL=$(expr "${INPUT}" == "flag") echo "$LABEL" 1 INPUT='flab' LABEL=$(expr "${INPUT}" == "flag") echo "$LABEL" 0 
+6
source share

This is probably simpler and may cover more test cases. You can get more detailed information about string comparisons and test cases using the "man test". Here is a pretty simple example.

 if [ "${INPUT}" == "flag" ]; then LABEL=${INPUT} fi echo ${LABEL} 
+1
source share

All Articles