In Bash, how can I check if a string begins with some value?

Tim picture Tim · Jan 31, 2010 · Viewed 675.7k times · Source

I would like to check if a string begins with "node" e.g. "node001". Something like

if [ $HOST == user* ]
  then
  echo yes
fi

How can I do it correctly?


I further need to combine expressions to check if HOST is either "user1" or begins with "node"

if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi

> > > -bash: [: too many arguments

How can I do it correctly?

Answer

Mark Rushakoff picture Mark Rushakoff · Jan 31, 2010

This snippet on the Advanced Bash Scripting Guide says:

# The == comparison operator behaves differently within a double-brackets
# test than within single brackets.

[[ $a == z* ]]   # True if $a starts with a "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

So you had it nearly correct; you needed double brackets, not single brackets.


With regards to your second question, you can write it this way:

HOST=user1
if  [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes1
fi

HOST=node001
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes2
fi

Which will echo

yes1
yes2

Bash's if syntax is hard to get used to (IMO).