EN
Bash - check if string is equal to
0
points
In this article, we would like to show you how to check if check if string is equal to another string in Bash.
Practical example
In this example, we use == operator to check if string is equal to another string inside the if statement.
script.sh file:
#!/bin/bash
string="abc"
if [ "$string" == "abc" ]; then
echo "The strings are equal"
fi
Note: this approach should be used in POSIX shells where other solutions may not work.
Run in command line:
./script.sh
Output:
The strings are equal
Altermative notation
1. test based solution
#!/bin/bash
string="abc"
if test "$string" == "abc"; then
echo "The strings are equal"
fi
Note:
[ ]notation is shorthand oftestcommand.
2. [[ ]] based solution
#!/bin/bash
string="abc"
if [[ "$string" == "abc" ]]; then
echo "The strings are equal"
fi
Note:
[[ ]]notation is like extendedtestcommand, adding additional features (e.g. regular expressions).