ZSH Gem #10: Backtick expansion

Posted by | Comments (0) | Trackbacks (0)

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.

Read more about backtick expansion:

Trackbacks

No Trackbacks for this entry.

Comments

No comments have been submitted yet. Be the first!

Write a comment:

HTML-Tags will be converted to Entities.
Textile-formatting allowed
Standard emoticons like :-) and ;-) are converted to images.
Design and Code Copyright © 2010-2014 Janek Bevendorff Content on this site is published under the terms of the GNU Free Documentation License (GFDL). You may redistribute content only in compliance with these terms. tweetbackcheck