Wandering Thoughts archives


An appreciation for the Posix $( ) command substitution syntax

The Posix standards for Unix sometimes get a bad rap (there are some crazy things in there, and some not so great ones), especially for the bits that they invented, but every so often I think that they did something absolutely right. The new Posix $(...) syntax for command substitution is one shining example of this; it is superior to the original Bourne shell syntax of `...` in so many ways. Here's some of the reasons that I like it.

First off, $(...) nests in a straightforward way without needing special quoting. All by itself this is a huge advantage; I've written before that any time you have multiple levels of quoting and processing going on, things go to hell. Nested $(...)'s let you avoid all of that; you don't need to quote anything, you just nest them and then read them outside in (or inside out). You can easily extract an inner $(...) to run it standalone to make sure that it returns the right result, and so on.

Next, $(...) is (in my opinion) easier to read and scan, because the edges of the command substitution are much easier to spot. ( and ) are much more visually distinctive than `, and run very little risk of being confused with other characters (unlike ` with ' and "). It's also clear whether you're dealing with the start or the end of a command substitution, unlike the Bourne shell case where a stray ` might be doing either and you need to carefully watch the surrounding context.

Finally, it's easier to see and remember that $(...) will expand inside "..."-quoted strings, because it looks just like other $ expansions. With traditional Bourne shell you had to remember that both $ and `...` expanded in that context.

(This cuts both ways when writing shell scripts; I find that I'm much more likely to use $() inside double quotes than I ever was with `...`, simply because it's easier to remember that it's possible.)

PS: before I started writing this entry, I had the incorrect impression that $(...) originated in bash. Bash is probably still the most common Bourne shell variant to find it supported (and I see that Solaris sh doesn't support it, not that this surprises me any more), but there are a number of others such as dash and various versions of Kenneth Almquist's sh implementation (originally called ash).

unix/PosixCommandSubstitution written at 00:24:16; 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.