3

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?

0

2 Answers 2

3

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 ."
0
2

You just have to use single quotes. Otherwise it will run pwd when the aliases are loaded, not when you call it.

https://unix.stackexchange.com/a/303675/282264

Example alias with pwd

alias youtube-mp3='docker run --rm -i -t -v $PWD:/data vimagick/youtube-dl -x --audio-format mp3'
1
  • This is the correct answer, it's insane that this is how it works, I would've never guessed.
    – innicoder
    Commented Feb 21, 2023 at 22:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .