Bash Check if string starts with uppercase alphabet

To check if string starts with uppercase alphabet in Bash scripting, you can use regular expression ^[A-Z](.*)$. In this expression ^ matches starting of the string, [A-Z] matches an uppercase alphabet, (.*) matches any other characters, and $ matches end of the string.

Examples

In the following script, we take a string in str which starts an uppercase alphabet. We shall programmatically check if string str starts with an uppercase alphabet using regular expression.

example.sh

#!/bin/bash
 
str="Apple@123"

if [[ $str =~ ^[A-Z](.*)$ ]]; then
  echo "String starts with uppercase."
else
  echo "String does not start with uppercase."
fi

Output

sh-3.2# ./example.sh 
String starts with uppercase.

Now let us take a value in the string str such that it does not start with an uppercase alphabet, but with a digit.

example.sh

#!/bin/bash
 
str="2Apple@123"

if [[ $str =~ ^[A-Z](.*)$ ]]; then
  echo "String starts with uppercase."
else
  echo "String does not start with uppercase."
fi

Output

sh-3.2# ./example.sh 
String does not start with uppercase.

References

Bash If Else

Conclusion

In this Bash Tutorial, we learned how to check if string starts with an uppercase alphabet using regular expression.