linux - [Solved-5 Solutions] How to compare two string variables in an 'if' statement in Bash - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
How to compare two string variables in an 'if' statement in Bash ?
Linux - Solution 1:
For string comparison, use:
if [ "$s1" == "$s2" ]
click below button to copy the code. By - Linux tutorial - team
For the a contains b, use:
if [[ $s1 == *"$s2"* ]]
click below button to copy the code. By - Linux tutorial - team
Ensure to add spaces between the symbols:
if [ "$s1" == "$s2" ]
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 2:
You need spaces:
if [ "$s1" == "$s2" ]
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 3:
You should be careful to leave a space between the sign of '[' and double quotes where the variable contains this:
if [ "$s1" == "$s2" ]; then
# ^ ^ ^ ^
echo match
fi
click below button to copy the code. By - Linux tutorial - team
The ^s show the blank spaces you need to leave.
Linux - Solution 4:
if [ "$a" = "$b" ]
click below button to copy the code. By - Linux tutorial - team
Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.
Also, be careful of your script header. It's not the same thing whether you use
#!/bin/bash
click below button to copy the code. By - Linux tutorial - team
or
#!/bin/sh
click below button to copy the code. By - Linux tutorial - team
Linux - Solution 5:
#!/bin/bash
s1="welcome to wikitechy"
s2="welcome to wikitechy"
if [ $s1 = $s2 ]
then
echo match
fi
click below button to copy the code. By - Linux tutorial - team
Without the double quotes and with only one equals.