Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 861
Tim Avatar asked Jan 31 '10 16:01

Tim


People also ask

How do you check if a variable starts with a string in bash?

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”.

How do you check if a string contains a substring in bash?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.

How do you check if a string has a substring in shell?

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 .

How do I read the first character of a string in bash?

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.


1 Answers

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).

like image 103
Mark Rushakoff Avatar answered Sep 29 '22 00:09

Mark Rushakoff