Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a variable contains only letters?

Tags:

bash

I tried to check the following case:

#!/bin/bash

line="abc"

if [[ "${line}" != [a-z] ]]; then
   echo INVALID
fi

And I get INVALID as output. But why?
Is there a check if $line contains only characters matching [a-z]?

like image 788
Software_t Avatar asked Jan 20 '26 14:01

Software_t


2 Answers

Use the regular expression matching operator =~:

#!/bin/bash

line="abc"

if [[ "${line}" =~ [^a-zA-Z] ]]; then
   echo INVALID
fi
like image 107
Sasha Kondrashov Avatar answered Jan 23 '26 19:01

Sasha Kondrashov


Works in any Bourne shell and wastes no pipes/forks:

case $var in
   ("")       echo "empty";;
   (*[!a-z]*) echo "contains a non-alphabetic";;
   (*)        echo "just alphabetics";;
esac

Use [!a-zA-Z] if you want to allow upper case as well.

like image 43
Jens Avatar answered Jan 23 '26 19:01

Jens