MacOS zsh alias pwd is incorrect

aliascommand linezsh

I recently switched to MacOS and some aliases in ZSH which were working on a linux system is giving me headaches in MacOS. To be specific, pwd variable inside alias is using the same directory where it was sourced from. I have to resource .zshrc from different directories for zsh to recognise pwd properly.

Here is what I mean. My content in .zshrc is:

alias myls="ls -lrth $(pwd)"

and here are the results:

~ source ~/.zshrc
~ cd ~
~ alias myls
... myls='ls -lrth /Users/myusername'

~ cd ~/Documents
~ alias myls
... myls='ls -lrth /Users/myusername' <--- It should list content for ~/Document
~ source ~/.zshrc
~ alias myls
... myls='ls -lrth /Users/myusername/Documents' <--- Sourcing again fixes it

Can someone tell me why do I have source my .zshrc again and again to be able to use $(pwd) while it works forever in linux in a single source?

Best Answer

The $(pwd) in your alias command is replaced immediately by its value returned from execution. This occurs at the creation of the alias, not when you want to use the alias. As shown after your first run of alias myls, the alias contains the exact path, not a call to pwd, so this will always use the original path set when you created the alias.

To use the current directory, don't run pwd, just use a relative path, which will always refer to the current directory when run.

alias myls="ls -lrth ."