Technology Guides and Tutorials

How to Check if a String Contains a Substring in Bash

Introduction

Bash is a powerful scripting language that can be used to perform a variety of tasks. One of the most common tasks is to check if a string contains a substring. This can be done using the built-in string manipulation functions in Bash. In this article, we will look at how to check if a string contains a substring in Bash.

Using the ‘if’ Statement

The most straightforward way to check if a string contains a substring is to use the ‘if’ statement. This statement takes a condition as an argument and will execute the code inside the statement if the condition is true. To check if a string contains a substring, we can use the ‘if’ statement with the ‘==’ operator. This operator checks if two strings are equal. We can use it to check if a string contains a substring by comparing the string to the substring.

For example, if we want to check if the string “Hello World” contains the substring “World”, we can use the following code:

if [ “$string” == “*World*” ]; then
echo “String contains substring”
fi

In this example, we are using the ‘if’ statement to check if the variable ‘string’ contains the substring “World”. If it does, the code inside the statement will be executed. In this case, we are simply printing a message to the console.

Using the ‘case’ Statement

Another way to check if a string contains a substring is to use the ‘case’ statement. This statement takes a pattern as an argument and will execute the code inside the statement if the pattern matches the string. To check if a string contains a substring, we can use the ‘case’ statement with the ‘*’ wildcard. This wildcard will match any character in the string.

For example, if we want to check if the string “Hello World” contains the substring “World”, we can use the following code:

case “$string” in
*World*)
echo “String contains substring”
;;
esac

In this example, we are using the ‘case’ statement to check if the variable ‘string’ contains the substring “World”. If it does, the code inside the statement will be executed. In this case, we are simply printing a message to the console.

more advanced example of using case:

#!/bin/bash

echo "What type of animal do you prefer?"
read ANIMAL

case $ANIMAL in
    "dog")
        echo "Dogs are great!"
        ;;
    "cat")
        echo "Cats are very nice!"
        ;;
    "fish")
        echo "Fish are beautiful to watch!"
        ;;
    *)
        echo "I'm not familiar with that type of animal."
        ;;
esac

Summary

In this article, we looked at how to check if a string contains a substring in Bash. We looked at two different methods for doing this: using the ‘if’ statement and using the ‘case’ statement. Both of these methods can be used to check if a string contains a substring in Bash.


Posted

in

, ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *