In this article we will provide you a bash script code with live demo to check if a substring is present at the end of a string or array. We will also see the code for conditions when substring is not at the end.
Code Example –
1. Check if substring is at the end of string –
#!/bin/bash var="This is a string" if [[ $var == *ing ]]; then printf '%s\n' "var ends with sub_string." fi # Output: # var ends with sub_string.
2. Check if substring is NOT at the end of string –
#!/bin/bash var="This is a string" if [[ $var != *str ]]; then printf '%s\n' "var does not end with sub_string." fi # Output: # var does not end with sub_string.
3. Check if substring is at the end of array –
#!/bin/bash arr=("This" "is a" "string") if [[ ${arr[*]} == *ing ]]; then printf '%s\n' "sub_string is at end of array." fi # Output: # sub_string is at end of array.
4. Check if substring is NOT at the end of array –
#!/bin/bash arr=("This" "is a" "string") if [[ ${arr[*]} != *str ]]; then printf '%s\n' "sub_string is not at end of array." fi # Output: # sub_string is not at end of array.