Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 538
tashuhka Avatar asked Nov 18 '14 17:11

tashuhka


People also ask

How do I assign a value to a variable in bash?

The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

How do I compare variables in bash?

Comparison Operators When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

What is == in bash script?

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

How do you assign an expression to a variable in shell script?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]


1 Answers

You can use expr:

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

INPUT='flab'
LABEL=$(expr "${INPUT}" == "flag")
echo "$LABEL"
0
like image 67
anubhava Avatar answered Oct 19 '22 14:10

anubhava