Search code examples
macosterminalprompt

\$ doesn't seem to be working when I set PS1 in terminal


I'm trying to understand customising the terminal on my mac. I've been playing around with changing the PS1 variable and I've found that \$ doesn't seem to work like the other escape characters. For example, below is a snippet from my terminal.

$PS1="\w\$"
~$echo $PS1
\w$

My question is, when I type echo $PS1 why does it display \w$ and not \w\$ ? and with PS1 set as above, if I was running the terminal as a superuser, would I see $ or #?


Solution

  • In bash, which is the default terminal shell on OSX, double quoted strings support some special characters such as \ and $. In the expression "\w\$", \$ is interpreted as an escaped literal for the character $.

    If you want $PS1 to contain the string \w\$, use single quotes:

    PS1='\w\$'
    

    Or, with double quotes, use \\ for backslash and \$ for the dollar sign:

    PS1="\\w\\\$"
    

    When $PS1 is set to \w$, the prompt will always end with a $, even as root. When $PS1 is set to \w\$, the prompt will end with a # if the effective uid is 0, otherwise $.