zsh alias that take a variable and expands it.

I have this in my .zshrc file:
Code Block
export dir1="Foo/one/"
export dir2="Foo/two/"
alias showdir='echo "dir name: " $1'

When the alias is entered it works like I would expect:
Code Block
dale: showdir dir1
dir name: dir1
dale: showdir dir2
dir name: dir2
dale: 


What I want instead is:

Code Block
dale: showdir dir1
dir name: Foo/one/
dale: showdir dir2
dir name: Foo/two/
dale: 

I have done a lot of searching and tried all sorts of character combinations to get the variable to expend in the echo alise and nothings seems to work.

Maybe I need a function? I have tried a few variations of functions too and I still have the same issue. The environmental verible name, when passed in, can't be expended to its defiintion.

I am missing something simple or is this really as hard as it seems?

Thanks!
Dale



Shell aliases are like text replacements, they do not support arguments at all.

If you want more complex functionality with arguments, you define a shell function in your .zshrc .

But for your example, all you are missing is a $ in front of the variable name to make the shell substitute it:

% echo $dir1
Foo/one/
% echo $dir2
Foo/two/

If you need to switch between directories faster, then I want to recommend zsh-z plugin – a command-line tool that allows you to jump quickly to directories that you have visited frequently in the past or recently.

As for the problem with $($1), I think it is an artificial problem in general. You already exported your project paths as environment variables (with export dir1="..."), so use them appropriately (e.g., showdir $1). You will get zsh's autocomplete for free for environment variables and can always type showdir $ then press TAB to see all the projects you have.

Also, a small recommendation, do not mess up with PWD within scripts and try to avoid direct cd commands. pushd/popd are better and more flexible.

zsh alias that take a variable and expands it.
 
 
Q