0

I want to use the name of the current directory in an alias in my .bashrc file. I'm using basename $PWD to get the current directory name and adding it using a nested quote in bash. My .bashrc has this command:

alias test="echo $(basename $PWD)"

The issue is that when I call this command in my terminal it doesn't use my current PWD but always uses the home PWD ~/. I.e.:

~/$ test
USERNAME
~/$ cd Documents
~/Documents$ test
USERNAME # <<< Should be Documents

Anyone know why the PWD doesn't update?

1 Answers1

2

Since you used double quotes, $(basename $PWD) is evaluated immediately and the result is used to define the alias. Use single quotes, or better yet, define a function instead of an alias.

my_func () {
    echo "$(basename $PWD)"
}

Don't name the alias test, because that shadows the standard test command (though it is more commonly referred to by its alias [).

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thank you! Solution was to change whole alias expression from double quotes `"` to single quotes `'`. This was sufficient to not "store" the PWD value upon sourcing of the `.bashrc` file. +1 – Steinn Hauser Magnússon Mar 07 '23 at 17:10
  • 3
    Get used to using functions for dynamically changing states. Aliases cause more problems than they are worth. Glad you solved your immediate problem. Good luck. – shellter Mar 07 '23 at 17:12
  • 1
    That's still a [useless use of `echo`](https://www.iki.fi/era/unix/award.html#echo) – tripleee Mar 07 '23 at 17:37