A little gotcha in shell scripts

November 29, 2005

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.

Written on 29 November 2005.
« How not to set up your DNS (part 3)
An advantage to introspection and an interactive interpreter »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Tue Nov 29 01:42:56 2005
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.