Bash Check if string contains only lowercase alphabets

To check if string contains only lowercase in Bash scripting, you can use regular expression ^[a-z]+$. In this expression ^ matches starting of the string, [a-z]+ matches one or more lowercase alphabets, and $ matches end of the string.

Examples

In the following script, we take a string in str which contains only lowercase alphabets. We shall programmatically check if string str contains only lowercase alphabets using regular expression.

example.sh

#!/bin/bash
 
str="apple"

if [[ $str =~ ^[a-z]+$ ]]; then
  echo "String contains only lowercase alphabets."
else
  echo "String does not contain only lowercase alphabets."
fi

Output

sh-3.2# ./example.sh 
String contains only lowercase alphabets.

Now let us take a value in the string str such that it not only contains lowercase alphabets, but also some uppercase alphabets and digits also.

example.sh

#!/bin/bash
 
str="Apple123"

if [[ $str =~ ^[a-z]+$ ]]; then
  echo "String contains only lowercase alphabets."
else
  echo "String does not contain only lowercase alphabets."
fi

Output

sh-3.2# ./example.sh 
String does not contain only lowercase alphabets.

References

Bash If Else

Conclusion

In this Bash Tutorial, we learned how to check if string contains only lowercase alphabets using regular expression.