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?
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
if syntax is hard to get used to (IMO).
If you're using a recent bash (v3+), I suggest bash regex comparison operator
if [[ "$HOST" =~ ^user.* ]]; then echo "yes" fi
this or that in a regex use
if [[ "$HOST" =~ ^user.*|^host1 ]]; then echo "yes" fi
Note - this is 'proper' regular expression syntax.
useand zero-or-more occurrences of
userand zero-or-more occurrences of any character, so
^user.*means match the pattern
user.*at the begin of $HOST.
If you're not familiar with regular expression syntax, try referring to this resource.
Note - it's better if you ask each new question as a new question, it makes stackoverflow tidier and more useful. You can always include a link back to a previous question for reference.