[Code Example] Check if string starts with substring or not using bash

Total
0
Shares

In this article we will provide you bash script code example to check if substring is present at the start of the string. This code won’t check any other occurrences of the substring.

Code Example –

1. Check if substring is at the start –

#!/bin/bash

var="This is a string"

if [[ $var == Th* ]]; then
    printf '%s\n' "var starts with sub_string."
fi

# Output:
# var starts with sub_string.

2. Check if substring is not at the start –

#!/bin/bash

var="This is a string"

if [[ $var != is* ]]; then
    printf '%s\n' "var does not start with sub_string."
fi

# Output:
# var does not start with sub_string.

3. Check if substring is at the start of array –

#!/bin/bash

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

if [[ ${arr[*]} == Th* ]]; then
    printf '%s\n' "sub_string is in start of array."
fi

# Output:
# sub_string is in start of array.

4. Check if substring is not at the start of the array –

#!/bin/bash

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

if [[ ${arr[*]} != is* ]]; then
    printf '%s\n' "sub_string is not in start of array."
fi

# Output:
# sub_string is not in start of array.

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