Simplest way to verify if a given string is a valid FQDN name?

I need to supply either '-name' or '-sname' when starting an Erlang VM depending on whether the given string is a fully qualified name (FQDN) or not. What would be the quickest and environment-independent way of validating that? I am more interested in using some bash command (like 'getent' or 'nslookup' or others) rather than a regex expression. Best if it works in Ubuntu, FreeBSD and Solaris without changes and can be used in bash's 'if' easily.


Solution 1:

Host seems to work:

jalderman@mba:/tmp$ cat test.sh
#!/bin/bash

for h in "bert" "ernie" "www.google.com"
do
    host $h 2>&1 > /dev/null
    if [ $? -eq 0 ]
    then
        echo "$h is a FQDN"
    else
        echo "$h is not a FQDN"
    fi
done

jalderman@mba:/tmp$ ./test.sh 
bert is not a FQDN
ernie is not a FQDN
www.google.com is a FQDN

Solution 2:

Unfortunately, I can not comment, but this is in fact a comment to the accepted answer: The solution does not check if the provided argument is really a FQDN. Simple host names that can actually be resolved will also qualify (simplest example: "localhost"). So perhaps the title of the question should be changed accordingly, if the question is not for a fqdn but simply for a resolving name. To actually add to the solution: If a fqdn is really required, you could simply check for a dot in the given name, like this:

is_fqdn() {
  hostname=$1
  [[ $hostname == *"."* ]] || return 1
  host $hostname > /dev/null 2>&1 || return 1
}

This will still allow for "localhost.", but thats technically a fqdn, anyways.