This article is part of the 2011 Advent calendar series “24 Outstanding ZSH Gems”. Each day between December 1st and December 24th an article will be published as part of this series showing one awesome feature of the Z Shell. Some of the features can of course also be found in other shells such as Bash, but the ZSH implementation is often superior.

Today's Gem is very short. I just want to mention an interesting feature of ZSH and that is backtick expansion.

The backtick operator is a well known operator to execute subcommands whose STDOUT can then be used to feed other programs on the command line. So for instance, if you want to search in files for an expression which you have in another file you could do it that way:

grep `cat expression` file1 file2 file3

Alternatively you could also use the alternate (and often better) syntax:

grep $(cat expression) file1 file2 file3

This is called command substitution and so far it's all nice and dandy and for shell scripts you'd normally leave it as that. But when you work directly on the command line, command substitution expressions sometimes grow very large resulting in a monster command.

Here ZSH's extended expansion mechanisms come in handy. As I told you before, you can expand each and every expression in ZSH directly on the command line by hitting the TAB key. So if you have a backtick expression, which has tons of commands in it, but the overall output is just a single word, this might be very beneficial. Just hit the TAB key after the closing backtick (or bracket if you use the alternate syntax) and ZSH will automatically evaluate the expression and replace it with the resulting output value. Provided our expression file from above contains the string some_expression you'll type the following:

% grep $(cat expression)<TAB>

and it'll be expanded to

% grep some_expression

then just type in the three file names as well, hit enter and there you go.

As I said: this is nothing for dynamic scripting but if you enter the command directly on the shell you might want to expand the backtick expressions to clean up the command line.