Often you may want to use Bash to check if a string ends with a specific value.
You can use the following methods to do so:
Method 1: Check if String Ends with Specific Value
if [[ $my_string == *A ]]
then
echo "String ends with A"
else
echo "String does not end with A"
fi
This particular example will check if the string variable named my_string ends with “A” and outputs the appropriate result.
Method 2: Check if String Ends with One of Several Specific Values
if [[ $my_string =~ .(A|C)$ ]]
then
echo "String ends with A or B"
else
echo "String does not end with A or B"
fi
This particular example will check if the string variable named my_string ends 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 Ends 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 ends with “C” or not.
We can use the following syntax to do so:
employee_ID="Manager005BC"
if [[ $employee_ID == *C ]]
then
echo "String ends with C"
else
echo "String does not end with C"
fi
The following screenshot shows how to use this syntax in practice:

This returns “String ends with C” since the string variable does indeed end with the letter C.
Example 2: Check if String Ends 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 ends with either “A” or “C”.
We can use the following syntax to do so:
employee_ID="Manager23350"
if [[ $employee_ID =~ .(A|C)$ ]]
then
echo "String ends with A or C"
else
echo "String does not end with A or C"
fi
The following screenshot shows how to use this syntax in practice:

This returns “String ends with A or C” since the string variable does indeed end with one of these two letters.
Note: The | operator stands for “or” and the $ operator stands for “the end of string” in regex.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Check if String Starts with Specific Value
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String
