Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find substring in shell script variable

Tags:

I have a string

$VAR="I-UAT";  

in my shell script code. I need a conditional statement to check if "UAT" is present in that string.

What command should I use to get either true or false boolean as output? Or is there any other way of checking it?

like image 350
batty Avatar asked Jul 25 '11 23:07

batty


People also ask

How do you find the substring of a string in a 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 you match a string in a shell script?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

How do you check if a string starts with a substring in shell script?

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


2 Answers

What shell? Using bash:

if [[ "$VAR" =~ "UAT" ]]; then     echo "matched" else     echo "didn't match" fi 
like image 161
Andrew Clark Avatar answered Oct 13 '22 14:10

Andrew Clark


You can do it this way:

case "$VAR" in   *UAT*)    # code when var has UAT   ;; esac 
like image 40
Diego Sevilla Avatar answered Oct 13 '22 14:10

Diego Sevilla