The \
character escapes the following (special) character. In this case, it escapes the $
, which we usually use to dereference a variable. When the shell evaluates a variable assignment, it first expands the right-hand-side of the expression. Without the \
before $PWD
, the shell expands $PWD
and assigns the result to PS1
.
However, with the \
, the shell treats $PWD
as a literal string, and assigns it as-is to PS1
, so that PS1
contains the string $PWD
, and not the expanded value of the variable $PWD
. When the shell is about to display the prompt, it once again carries out variable expansion, and this time, because $PS1
contains $PWD
, without the \
, the shell successfully expands it to the current directory.
The same approach can be used to create dynamic variable names in shell scripts (the NetBSD rcNG
system uses this quite widely, especially in scripts controlling network interfaces, where the number of network adapter designations in NetBSD and FreeBSD make it impractical to explicitly code for each one).
export PS1='$PWD $'
(single, not double, quotes), does that work as well?`. You'll discover that it doesn't work as soon as you
cd` to another directory. Now think what$PWD
means and consider why the prompt will always show the same directory regardless of where you're at.