Why when I enter this command the prompt changes to my directory?
PS1='$(pwd)'
I am using single quotes, which means no interpolation , a.k.a echo '$(pwd)'
——→ $(pwd)
Furthermore, say that we clarified why this works… why is it functioning differently from PS1=$(pwd)
? (no quotes at all)
By different I mean that if I use the quotes then the prompt will keep changing to my current directory as I navigate through the terminal. But if I don't use quotes, then the prompt will always remain the directory that I was in when I first entered the command PS1=$(pwd)
why?
Best Answer
When you simply assign a value to a variable, the
$(...)
expression is evaluated unless it is enclosed in single quotes (or backslash-escaped). To understand, try and compare these two:The value of
A
immediately becomes the string/home/yourusername
and obviously it's not remembered where this string comes from, it stays the same even if you change directory. The value ofB
, however, becomes the literal string$(pwd)
without getting interpreted.Now, in the value of
PS1
something special happens: whenever the prompt is printed, certain special constructs are interpreted, e.g. the command substitution$(...)
is performed exactly the way it happened above at the assignment to theA
variable. Obviously if yourPS1
contains the literal string of your home directory (as above withA
) then there's no way it could change. But if it contains the string$(pwd)
(as above withB
) then it is evaluated whenever the prompt is printed and hence your actual directory is displayed.