unixpathzshaliaspwd

Why does the alias I have created not execute in the path I am expecting?


I have created an alias that is intended to copy to my clipboard whichever path I am in, in the terminal.

The alias is in my .zshrc file.

The alias looks as follows:

alias cpath="echo -n `pwd`|pbcopy"

When I execute the following command in my terminal it always works:

echo -n `pwd`|pbcopy

However, when I use the alias cpath, it copies whichever path was the path when I first opened a particular terminal. For example, if I open a terminal in the /Users/tommyrharper directory, then I run cpath, it will copy the following path to my clipboard: /Users/tommyrharper.

If I then cd into my Documents folder, then run cpath, then it will still just add /Users/tommyrharper to my clipboard.

However If I then directly run echo -n `pwd`|pbcopy it will add /Users/tommyrharper/Documents to my clipboard.

If I initially opened a terminal in /Users/tommyrharper/Documents and then I run cpath, then it will add /Users/tommyrharper/Documents to my clipboard.

But then again if I cd into my Notes directory, then I run cpath, it will still just add /Users/tommyrharper/Documents to my clipboard.

Why is my alias not behaving in the same way as when I directly enter the command in the terminal?

And is there a way to get my alias to work as expected?


Solution

  • This happens because the backtick command substitution in your alias (`pwd`) gets run when zsh sources .zshrc when it starts up. This is because you have used doubles quotes, which evaluate substitutions.

    You can confirm this by running alias cpath, which will display the definition of the alias, which should now include a path instead of a literal `pwd`.

    If you instead define your alias like this with single quotes (which do not evaluate substitutions):

    alias cpath='echo -n `pwd`|pbcopy'
    

    it will work as expected.

    More details on the different quoting styles and substitutions can be found here: https://mywiki.wooledge.org/Quotes