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?

  • 2
    Use single quotes instead of double quotes in your alias definition. Also, there is no need for an argument in your ls command. – fd0 Aug 22 '19 at 11:18
  • @fd0 The question is not specific to ls command but to any command that uses pwd. For instance docker -v flag does not take relative paths, hence aliasing docker from zsh has to have a pwd within double quotes. What do you suggest in that case? – ashutosh Aug 23 '19 at 12:18
  • If you had tried my comment then you should realize that the single quotes prevent the command substitution ( $(pwd) ) from happening when the alias is loaded into memory. Thus using ls as an example, alias myls='ls -lrth $(pwd)' would give you the expected behavior. We could even use the shell parameter PWD in the example- alias myls='ls -lrth $PWD' . In this case parameter expansion does not take place when the alias is loaded and the parameter only expands when you use the alias. docker is third party software that I have little knowledge of. – fd0 Aug 23 '19 at 19:21

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 ."
|improve this answer|||||
  • Ok that works. However, the issue now is in my one of docker command alias. I use alias php="docker run -v $(pwd):/var/www/html" php:7.2-cli php to run PHP commands in my machine. Since docker doesn't support relative paths, using . notation won't work here. – ashutosh Aug 22 '19 at 10:21

You must log in to answer this question.

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