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 to do it correctly?
You can select just the part of the string you want to check:
For your follow-up question, you could use an OR:
Adding a tiny bit more syntax detail to Mark Rushakoff's highest rank answer.
The expression
Can also be written as
The effect is the same. Just make sure the wildcard is outside the quoted text. If the wildcard is inside the quotes it will be interpreted literally (i.e. not as a wildcard).
While I find most answers here quite correct, many of them contain unnecessary bashisms. POSIX parameter expansion gives you all you need:
and
${var#expr}
strips the smallest prefix matchingexpr
from${var}
and returns that. Hence if${host}
does not start withuser
(node
),${host#user}
(${host#node}
) is the same as${host}
.expr
allowsfnmatch()
wildcards, thus${host#node??}
and friends also work.Another thing you can do is
cat
out what you are echoing and pipe withinline cut -c 1-1
doesn't work, because all of [, [[ and test recognize the same nonrecursive grammar. see section CONDITIONAL EXPRESSIONS in your bash man page.
As an aside, the SUSv3 says
you'd need to write it this way, but test doesn't support it:
test uses = for string equality, more importantly it doesn't support pattern matching.
case
/esac
has good support for pattern matching:it has the added benefit that it doesn't depend on bash, the syntax is portable. from the Single Unix Specification, The Shell Command Language: