0

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=master01.nassa.com
[[ $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?

4

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=master01.naSsa.com
[[ $hostname  =~ [A-Z] ]] && echo "hostname is not ok"
hostname is not ok

Or

hostname=master01.nassa.com
[[ $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?

0
2

For a /bin/sh solution:

hostname=master01.nassa.com

case $hostname in
    *[A-Z]*)
        echo 'Not ok' ;;
    *)
        echo 'Ok'
esac

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'
else
    echo 'Ok'
fi

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.

1
  • very nice answer , well done
    – yael
    Nov 25 '18 at 12:41
1
hostname=master01.nassa.com
[[ "$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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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