📜  bash if substring - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:13:36.746000             🧑  作者: Mango

Bash If Substring - Shell-Bash

Introduction

In bash scripting, the if statement is used to perform different actions based on certain conditions. One common use case is checking if a string contains a specific substring. This guide will explain how to use the if statement to check for substrings in bash.

Syntax

The syntax for checking if a substring exists in a string using the if statement is as follows:

if [[ $string = *substring* ]]; then
    # Action to take if substring is found in the string
else
    # Action to take if substring is not found in the string
fi
Explanation
  • The [[ $string = *substring* ]] condition checks if the variable $string contains the substring substring. The = operator is used for string comparison and the * wildcard characters are used to match any characters before and after the substring.
  • If the condition is true (i.e., the substring is found in the string), the code inside the if block will be executed.
  • If the condition is false (i.e., the substring is not found in the string), the code inside the else block will be executed.
Example

Let's see an example where we check if a string contains the substring "bash":

#!/bin/bash

string="Shell scripting with bash"
substring="bash"

if [[ $string = *$substring* ]]; then
    echo "The string contains the substring 'bash'"
else
    echo "The string does not contain the substring 'bash'"
fi

Output:

The string contains the substring 'bash'

In this example, the condition [[ $string = *$substring* ]] is true because the substring "bash" is present in the string "Shell scripting with bash". Therefore, the code inside the if block is executed and the message "The string contains the substring 'bash'" is printed.

Conclusion

Checking if a substring exists in a string using the if statement in bash is a common task in shell scripting. By following the syntax and examples provided in this guide, you can easily incorporate substring checking into your bash scripts.