Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

How do I check if a variable is in [A-Z]

I want something like this:

read var

while [ $var in [A-Z] ]
 #code here

How to achieve this?

share|improve this question
Is $var a single character or do you want to test that it contains only letters? – terdon Sep 26 '13 at 16:44

3 Answers 3

In bash, you can use a pattern on the right hand side of a == in a [[ ... ]]:

read var
LC_ALL=C # Turn off locale.
if [[ $var == [A-Z] ]] ; then
    echo yes

Turning off locale might be needed if you do not want y to be in A-Z.

share|improve this answer

The simple one liner would be:

re='[a-zA-Z]'; if [[ Z =~ $re ]]; then echo "Match"; else echo "No match"; fi

The full script would be:


read -p "Enter a char or string > " var

if [[ "$var" =~ $re ]]; then
    echo "Entered string matches."
    echo "Entered string does not match";
share|improve this answer

If you don't want to rely on Bash's regular expressions:

remainder=$(tr -d A-Z <<<$var)
while [ ! -z $remainder ];do
    read -p "Invalid value entered. Please try again." var
    remainder=$(tr -d A-Z <<<$var)

I'm guessing you want to use this for input validation.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.