Wandering Thoughts archives


A Unix shell glob trick

This is the kind of trick where first I show the trick and then I explain it:

$ touch a-b; mkdir a-c
$ cd a-*
sh: cd: a-b: Not a directory
$ cd a-*/
$ pwd

(This is also a good illustration of quality of implementation in error handling. A number of non-bash Bourne shells will report things like 'cd: too many arguments', while bash would happily work if a-b happened to be a directory.)

What this does is use a trick to pick the directory out of an otherwise ambiguous wildcard expansion. When there's a / on the end, the shell will conveniently restrict the wildcard expansion to directories, or in the cases where I usually wind up using this, the directory.

(The usual case for me is that I have just unpacked foo-1.2.tar.gz, creating foo-1.2, and now I want to cd into the latter without having to type the full name (my usual shell doesn't have filename completion by default), but there are others that come up every so often.)

Reading very carefully between the lines, I think that this behavior is required by the SUS. In general a shell might as well support this, since you can always write the wildcard as 'a-*/.' to force the issue.

A closely related trick can be used to find all of the subdirectories in your current directory (or in general, somewhere): 'echo */.'. In theory 'echo */' should be equivalent, but many shells seem to need the issue forced. I don't understand why those shells need this; that they behave differently for these two cases makes my head hurt.

(Ironically, bash gets this one right, and I believe that getting it right is the SUS-required behavior.)

unix/ShellGlobTrick written at 00:18:03; Add Comment

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.