Bash: How to Check if String Starts with Specific Value


Often you may want to use Bash to check if a string starts with a specific value.

You can use the following methods to do so:

Method 1: Check if String Starts with Specific Value

if [[ $my_string == A* ]]
then
    echo "String starts with A"
else
    echo "String does not start with A"
fi

This particular example will check if the string variable named my_string starts with “A” and outputs the appropriate result.

Method 2: Check if String Starts with One of Several Specific Values

if [[ $my_string =~ ^(A|B) ]]
then
    echo "String starts with A or B"
else
    echo "String does not start with A or B"
fi

This particular example will check if the string variable named my_string starts with “A” or “B” and outputs the appropriate result.

The following examples show how to use each method in practice.

Example 1: Check if String Starts with Specific Value in Bash

Suppose we have a string variable named employee_ID that contains the ID of some employee at a particular company and we would like to check if it starts with “M” or not.

We can use the following syntax to do so:

employee_ID="Manager23350"

if [[ $employee_ID == M* ]]
then
    echo "String starts with M"
else
    echo "String does not start with M"
fi

The following screenshot shows how to use this syntax in practice:

Bash check if string starts with value

This returns “String starts with M” since the string variable does indeed start with the letter M.

Example 2: Check if String Starts with One of Several Specific Values in Bash

Suppose we have a string variable named employee_ID that contains the ID of some employee at a particular company and we would like to check if it starts with either “A” or “M”.

We can use the following syntax to do so:

employee_ID="Manager23350"

if [[ $employee_ID =~ ^(A|M) ]]
then
    echo "String starts with A or M"
else
    echo "String does not start with A or M"
fi

The following screenshot shows how to use this syntax in practice:

Bash check if string starts with one of several values

This returns “String starts with A or M” since the string variable does indeed start with one of these two letters.

Note: The | operator stands for “or” and the ^ operator stands for “the beginning of string” in regex.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String
Bash: How to Count Number of Columns in File

Leave a Reply