zsh Event Tricks

I’ve been a Z shell (zsh) user for perhaps 15 years, being a tcsh user before that.

Unfortunately, it appears that there is no zsh book from my preferred technical books publishers, O’Reilly, Pragmatic Programmers or Manning. Thus my knowledge is from the zshall man page (all 15,000+ lines, when you can find it) and from experience.

I’d like to share a few examples of what one can do with this shell, and I’m going to go from most to least recent in what I’ve found and used.

The latest thing that I learned is how to get previous arguments. I’d known about “!!” to get the previous full command line, so if I needed the second argument, I’d do “!!<tab>”, then backspace (or search back, i.e., “<ctrl>r”) to the end of the argument, delete (“<ctrl>k”) to the end of the line, then move to the beginning of the argument “<alt>b”, then delete word-by-word “<alt><backspace>” through all the other arguments that “!!<tab>” expanded to.

What a mess, although doing that a few hundred times made it easy, although far from efficient.

So when perusing the 15,000 zshall man page (one day I’ll make that my summer reading) I saw that one can write “!!:2” to get the second argument of the previous line. Hurrah. Note that, of course, arguments are zero-indexed.

And the leading “!!” can be of the form “!-3”, meaning “the third most recent”, and “!-1” is the same as “!!”.

I haven’t used this much, but the word designators (the argument after the “:”) can be a range, so for the second through fourth argument of the command before last, the command would be “!-2:2-4”. If there is no starting number for the range, e.g., “!!:-2”, then that is the same as 0 through N, the first N+1 arguments from the earlier command.

In action, this looks like:

designators

Another form of syntax, as seen in the example above, is !N, where N is the number of the command line to reference. In the example, 3066 is the command line in history, so !3066:3 refers to the fourth word in that command.

In a subsequent post, I’ll discuss the prompt that you just saw, and why having the command-line number is useful.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s