An incorrect superstition about running commands in the Bourne shell

October 26, 2019

Every so often, I wind up writing some bit of shell script that wants to execute an entire command line that it has been passed (program and all). For years I have written this as follows:

# re-execute the command line
cmd="$1"; shift
"$cmd" "$@"

Some version of this has crept into innumerable shell scripts, partly for reasons beyond the scope of this entry. I've always considered it just a little Bourne irritation that "$@" didn't let you directly run commands and you had to peel off the command first.

Except that that's wrong, as I found out as I was just about to write an entry complaining about it. Both Bash and several other implementations of the Bourne shell are perfectly happy to let you write this as the obvious:

# re-execute the command line

I've apparently spent years programming via superstition. Either I got this wrong many years ago and it stuck, or at some point I had to use some version of the Bourne shell where this didn't work. Well, at least I know better now and I can do it the easy way in future scripts.

(One case for this sort of re-execution is if you've got a generic script for running other commands with locking. The script is given a lock name and the command line to run under the lock, and it will wind up wanting to do exactly this operation.)

PS: Since this seems to be so widely supported across various versions of the Bourne shell, I assume that this is either POSIX compatible or even POSIX mandated behavior. I haven't bothered to carefully read the relevant specification to be sure of that, though.

Written on 26 October 2019.
« Third party ClamAV signatures seem to include a lot of phish and other spam
My common patterns in shell script verbosity (for sysadmin programs) »

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

Last modified: Sat Oct 26 00:06:18 2019
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.