Rule #1: There are no rules.

ZSH: Quick Quoting

| Comments

Some spelunking in the ZSH manual last week revealed some real treasures I’ve gotten good use out of already: ESC-" and ESC-'.

ESC-" runs the command escape-region, which you can use to have zsh escape any arbitrary piece of text for you. No more pasting in URLs, file paths, or regular expressions and trying to manually sort out what characters you need to escape—just let the shell do it for you.

Like so many other conventions, ZSH borrows from Emacs the idea of the region, a (possibly invisible) span of text from the point where the user last placed the mark to the current cursor position. Many commands use the region as an indication of what area of text to operate upon. In both Emacs and ZSH, the most basic way to set the mark is with CTRL-SPC.

So if we’ve just typed in the following text…

$ echo I *love* zsh!

…I can escape the parameters to echo with CTRL-SPC ESC-3 ESC-b ESC-" (set-mark-command, digit-argument (3), backward-word, escape-region) and voila!:

$ echo 'I *love* zsh!'

But something I’ve used even more than that is to set the mark in advance of pasting in something I know I’ll want to escape. So if I have a URL on the pasteboard that I want to curl that might contain nasty characters I’ll enter:

$ curl -O

Then hit CTRL-SPC CMD-V ESC-" and end up with a properly escaped URL, ready to be curled:

$ curl -0 ''

BTW, it is smart enough to escape existing quotes in the region.

You can also use the similar command quote-line (on ESC-') to escape the entire line of input, but I haven’t found as much use for that yet.