we want to check the hostname on machines the rule should be like this:

each hostname must be only with small letters each hostname is FQDN

we try this

[[ $hostname  =~ ^[a-z.a-z.a-z]+$ ]] && hostname is ok

but in spite the hostname is valid , it isn't print "hostname is ok"

what is the right syntax , where we are wrong?

3 Answers 3


Your regex is somehow wrong and the part after && misses echo. Instead of writting complex regexs to validate the hostname you can consider to do the opposite:

[[ $hostname  =~ [A-Z] ]] && echo "hostname is not ok"
hostname is not ok


[[ $hostname  =~ [A-Z] ]] || echo "hostname is ok"
hostname is ok

Moreover to avoid complex situation you better define locale to C or posix using LC_ALL=C
See : Why does [A-Z] match lowercase letters in bash?


For a /bin/sh solution:


case $hostname in
        echo 'Not ok' ;;
        echo 'Ok'

The "Not ok" branch is taken if the value of $hostname contains any uppercase characters (this may depend on your locale settings), while the "Ok" branch is taken if the "Not ok" branch isn't taken.

This is similar to the bash-specific (and also ksh and zsh)

if [[ "$hostname" == *[A-Z]* ]]; then
    echo 'Not ok'
    echo 'Ok'

Your test with the regular expression ^[a-z.a-z.a-z]+$ is identical to a test with ^[a-z.]+$ (since a [...] character class matches a single character and repeated a-z inside it won't make a difference). This will actually do what you say it does, which is to allow only hostnames with lowercase letters (and dots). The issue is that your hostname also contains digits. To allow for these too, you would have to use ^[a-z0-9.]+$. In this case though, it may be easier to test for the smaller set of characters that are not allowed, which is what I do above.

  • very nice answer , well done
    – yael
    Nov 25, 2018 at 12:41
[[ "$hostname"  =~ ^[a-z]+\.[a-z]+\.[a-z]+$ ]] && echo hostname is ok

is your example with some bugs fixed but for more accurite validation look at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .