Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the `pwd` in an `alias`?

Tags:

zsh

zshrc

Is there a way I can get the pwd in an alias in my .zshrc file? I'm trying to do something like the following:

alias cleanup="rm -Rf `pwd`/{foo,bar,baz}"

This worked fine in bash; pwd is always the directory I've cd'd into, however in zsh it seems that it's evaluated when the .zshrc file is first loaded and always stays as my home directory. I've tested using with a really simple alias setup, but it never changes.

How can I have this change, so that calling the alias from a subdirectory always evaluates as that subdir?

EDIT: not sure if this will help, but I'm using zsh via oh-my-zsh on the mac.

like image 430
Phillip B Oldham Avatar asked Apr 06 '11 12:04

Phillip B Oldham


1 Answers

When your .zshrc is loaded, the alias command is evaluated. The command consists of two words: a command name (the builtin alias), and one argument, which is the result of expanding cleanup="rm -Rf `pwd`/{foo,bar,baz}". Since backquotes are interpolated between double quotes, this argument expands to cleanup=rm -Rf /home/unpluggd/{foo,bar,baz} (that's a single shell word) where /home/unpluggd is the current directory at that time.

If you want to avoid interpolation at the time the command is defined, use single quotes instead. This is almost always what you want for aliases.

alias cleanup='rm -Rf `pwd`/{foo,bar,baz}'

However this is needlessly complicated. You don't need `pwd/` in front of file names! Just write

alias cleanup='rm -Rf -- {foo,bar,baz}'

(the -- is needed if foo might begin with a -, to avoid its being parsed as an option to rm), which can be simplified since the braces are no longer needed:

alias cleanup='rm -Rf -- foo bar baz'
like image 105
Gilles 'SO- stop being evil' Avatar answered Sep 30 '22 01:09

Gilles 'SO- stop being evil'