What's wrong with this as a way to turn a hostname into a FQDN?
FQDN=$(getent hosts "$SHORT" | awk '{ print $2 }')
Answer: getent can return multiple lines of results. This only happens if the system is configured to check /etc/hosts before DNS and if /etc/hosts lists the hostname multiple times. There may be other ways this can happen too, but that's the situation that bit me. Of course, there shouldn't be multiple repeated lines in /etc/hosts but nothing forbids it.
As a result you can end up with FQDN="hostname.dom.ain hostname.dom.ain
which, and I'm just guessing here, is going to cause problems elsewhere in your script.
The solution is to be a bit more defensive and only take the first line of output:
FQDN=$(getent hosts "$SHORT" | head -1 | awk '{ print $2 }')
Of course, there is still error-checking you should do, but I'll leave that as an exercise to the reader. (Hint: You can check if $?
is non-zero; you can also check if FQDN is the null string.)
Technically the man page covers this situation. It says the command "gathers entries" which, being plural, is a very subtle hint that the output might be multiple lines. I bet most people reading the man page don't notice this. It would be nice if the man page explicitly warned the user that the output could be multiple lines long.
P.S. I'm sure the first comment will be a better way to do the same thing. I look forward to your suggestions.
Your command makes a lot of assumptions. It's unclear what your actual intent really is, here. For example, in my /etc/hosts file, I have:
1.2.3.4 hostname hostname.domain.com
And, "getent hosts hostname" produces that line - it's very similar functionally to "grep '\shostname\s' /etc/hosts".
There's a lot of things to be careful about with your approach ...