[Code Example] Check if substring is present in string or array using bash

Total
0
Shares

In this article I will provide you the bash script code to check if a substring is present in string or an array. This code works for both strings and array.

Code Example –

1. Check on string

#!/bin/bash

var="This is a string"

[[ $var == *is* ]] && echo "string matched"

# Output:
# string matched

2. Check on array –

#!/bin/bash

arr=("This" "is a" "string")

[[ ${arr[*]} == *is* ]] && echo "array matched"

# Output:
# array matched

3. Check if NOT in string

#!/bin/bash

var="This is a string"

([[ $var != *is* ]] && echo "string matched") || echo "string not matched"

# Output:
# string not matched

4. Using if conditions –

#!/bin/bash

if [[ $var == *sub_string* ]]; then
    printf '%s\n' "sub_string is in var."
fi

# Inverse (substring not in string).
if [[ $var != *sub_string* ]]; then
    printf '%s\n' "sub_string is not in var."
fi

# This works for arrays too!
if [[ ${arr[*]} == *sub_string* ]]; then
    printf '%s\n' "sub_string is in array."
fi

5. Using switch conditions –

case "$var" in
    *sub_string*)
        # Do stuff
    ;;

    *sub_string2*)
        # Do more stuff
    ;;

    *)
        # Else
    ;;
esac

Inspired from Dylan Araps

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like