Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

zsh - Get the `pwd` in an `alias`?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...