Take the 2-minute tour ×
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] ]
do
 #code here
done

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
add comment

3 Answers

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
fi

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

share|improve this answer
add comment

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:

#!/bin/bash

re='[a-zA-Z]'
read -p "Enter a char or string > " var

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

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)
done

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

share|improve this answer
add comment

Your Answer

 
discard

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.