Bash – Check if string ends with specific suffix

To check if a string ends with specific suffix string in Bash scripting, you can use the following condition.

</>
Copy
$string1 == *$suffix

where string1 is a whole string, and suffix is a suffix string.

If the string string1 ends with suffix string, then the above expression returns true, else it returns false.

Example

In the following script, we take two strings in string1 and suffix, and check if string string1 ends with the suffix.

example.sh

</>
Copy
#! /bin/bash

string1="hello world"
suffix="world"

if [[ $string1 == *$suffix ]]; then
  echo "String ends with given suffix."
else
  echo "String does not end with given suffix."
fi

Output

sh-3.2# ./example.sh 
String ends with given suffix.

References

Bash If Else

Conclusion

In this Bash Tutorial, we learned how to check if a string ends with a specific suffix string.