Bash – Check if string contains only uppercase

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

Examples

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

example.sh

</>
Copy
#!/bin/bash
 
str="APPLE"

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

Output

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

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

example.sh

</>
Copy
#!/bin/bash
 
str="Apple123"

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

Output

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

References

Bash If Else

Conclusion

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