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?
We can use the double equals ( == ) comparison operator in bash, to check if a string starts with another substring. In the above code, if a $name variable starts with ru then the output is “true” otherwise it returns “false”.
To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.
Using Regex Operator Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk .
To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With