A little gotcha in shell scripts
I have a script called '
nsaddrs', which lists the IP addresses of
the nameservers for a given domain. It is basically:
addr `dig +short ns $1`
addr is one of my utility programs; it does IP address lookups for
hostnames. Normally you give it hostnames on the command line, but for
bulk lookups you can give it no arguments and it will read hostnames
from standard input, one per line.
Then one day I used
nsaddr on a domain that didn't exist and it
'hung'. After I stopped thinking that the nameservers were being
really slow, I worked out the bug: when
dig couldn't find any
nameservers it didn't produce any output, and when that happened
addr had no arguments, so it was trying to read hostnames from the
terminal. (Naturally I wasn't supplying any.)
The solution is simple:
addr `dig +short ns $1` </dev/null
There's a fair number of Unix utilities that have this 'process arguments or standard input' behavior. Any time a shell script uses one of these program in this pattern, this little gotcha can be waiting in the wings.