Brief: This example will help you to check if one string contains another substring in a bash script.
You can use wildcard character *
to find if a string contains a substring in a bash script. Here is a simple example
1 2 3 4 5 6 7 | #!/bin/bash str="This is the main string" if [[ $str = *main* ]]; then echo "Yes" fi |
Output:
Yes
If you have multi-word substring, use double quote around the string:
1 2 3 4 5 6 7 | #!/bin/bash str="This is the main string" if [[ $str = *"is the main"* ]]; then echo "Yes" fi |
Output:
Yes
Another Example
This is another example to read a file line by line and check if a string contains a specific substring and do some operation on it. For example, check all the users in /etc/passwd having shell /bin/bash.
1 2 3 4 5 6 7 8 | #!/bin/bash while read line; do if [[ $line = *"/bin/bash"* ]]; then //do something here fi done < /etc/passwd |