How to compare strings in Bash
Using variables in if statements
if [ "$x" = "valid" ]; then
echo "x has the value 'valid'"
fi
If you want to do something when they don't match, replace =
with !=
. You can read more about string operations and arithmetic operations in their respective documentation.
Why do we use quotes around $x
?
You want the quotes around $x
, because if it is empty, your Bash script encounters a syntax error as seen below:
if [ = "valid" ]; then
Non-standard use of ==
operator
Note that Bash allows ==
to be used for equality with [
, but this is not standard.
Use either the first case wherein the quotes around $x
are optional:
if [[ "$x" == "valid" ]]; then
or use the second case:
if [ "$x" = "valid" ]; then
Linux shell programming string compare syntax
These pages explain the various comparison operators in bash:
- http://www.tech-recipes.com/rx/209/bournebash-shell-scripts-string-comparison/
- http://tldp.org/LDP/abs/html/comparison-ops.html
- http://www.faqs.org/docs/Linux-HOWTO/Bash-Prog-Intro-HOWTO.html#ss11.2
On the second linked page, you will find:
==
is equal to
if [ "$a" == "$b" ]
This is a synonym for =.
How do I compare two string variables in an 'if' statement in Bash?
For string equality comparison, use:
if [[ "$s1" == "$s2" ]]
For string does NOT equal comparison, use:
if [[ "$s1" != "$s2" ]]
For the a
contains b
, use:
if [[ $s1 == *"$s2"* ]]
(and make sure to add spaces between the symbols):
Bad:
if [["$s1" == "$s2"]]
Good:
if [[ "$s1" == "$s2" ]]
Linux Shell Script - String Comparison with wildcards
When using ==
or !=
in bash you can write:
if [[ $t1 == *"$t2"* ]]; then
echo "$t1 and $t2 are equal"
fi
Note that the asterisks go on the outside of the quotes and that the wildcard pattern must be on the right.
For /bin/sh, the =
operator is for equality only, not pattern matching. You can use case
for pattern matching though:
case "$t1" in
*"$t2"*) echo t1 contains t2 ;;
*) echo t1 does not contain t2 ;;
esac
If you're specifically targeting Linux, I would assume the presence of /bin/bash.
bash script syntax to compare strings as integers
Put spaces around command names like [[
and [
.
For example:
if [[ "$ITEMCOUNT" -eq "$ONE" ]]
then
or, if you like semicolons:
if [[ "$ITEMCOUNT" -eq "$ONE" ]]; then
And:
if [ $DIRCOUNT == "1" ]; then
or (better use of quotes):
if [ "$DIRCOUNT" == "1" ]; then # Or just 1 (no quotes around it)
Because these are commands, you need spaces around the components of the expression too (as you have them already). Don't skimp on spaces in shell scripts (but also don't use them where they are not allowed, such as around the =
in a variable assignment).
Note that both the [[
command and the ==
operator for [
are Bash extensions compared to the POSIX shell.
Shell equality operators (=, ==, -eq)
=
and ==
are for string comparisons-eq
is for numeric comparisons-eq
is in the same family as -lt
, -le
, -gt
, -ge
, and -ne
==
is specific to bash (not present in sh (Bourne shell), ...). Using POSIX =
is preferred for compatibility. In bash the two are equivalent, and in sh =
is the only one that will work.
$ a=foo
$ [ "$a" = foo ]; echo "$?" # POSIX sh
0
$ [ "$a" == foo ]; echo "$?" # bash-specific
0
$ [ "$a" -eq foo ]; echo "$?" # wrong
-bash: [: foo: integer expression expected
2
(Note: make sure to quote the variable expansions. Do not leave out the double-quotes above.)
If you're writing a #!/bin/bash
script then I recommend using [[
instead. The double square-brackets [[...]]
form has more features, a more natural syntax, and fewer gotchas that will trip you up. For example, double quotes are no longer required around $a
:
$ [[ $a == foo ]]; echo "$?" # bash-specific
0
See also:
- What's the difference between [ and [[ in Bash?
Compare String with list of strings in bash
Assuming the az ml
command returns a json array string and you want to
check if the array includes the value of variable SERVNAME
, would you
please try:
SERVNAME="ner"
SERVICE='[ "ner", "aks-gpu-ner-0306210907", "aks-gpu-ner-30012231", "aks-gpu-ner-1305211336"]'
if [[ $SERVICE =~ "\"$SERVNAME\"" ]]; then
echo "Service Found"
# put your command here to update the service
else
echo "Service Not Found"
# put your command here to deploy new service
fi
The regex operator $SERVICE =~ "\"$SERVNAME\""
matches if the string $SERVICE
contains the substring $SERVNAME
enclosed with double quotes.
If jq
is available, you could also say:
result=$(echo "$SERVICE" | jq --arg var "$SERVNAME" '. | index($var)')
if [[ $result != "null" ]]; then
echo "Service Found"
else
echo "Service Not Found"
fi
Related Topics
What Ncurses Frameworks Are Available for Bash
Berkeley Db Mismatch Error While Configuring Ldap
Find The Depth of The Current Path
How to Do a While Loop with a String Redirected into It
Does I2C Driver Need to Be Implemented Just Like Any Other Character Device Driver
Rodbc Not Recognizing My Odbc Settings
How to View Svn Diff in Vimdiff Style in Svn
Bash Command That Prints a Message on Stderr
Can Multiple .Gz Files Be Combined Such That They Extract into a Single File
How to Give File Permission to a Specific User in a Group
What Is The Equivalent of /Proc/Cpuinfo on Freebsd V8.1
Jenkins Failed to Start in Linux
How to Set Default Arguments for "Ls" in Linux
Amazon Ec2 Lost Private Key, How to Get Access to The Server