13

When logging into root, the default prompt when echoed is \s-\v\$, which shows as bash-4.2#. I am trying to play around with the bash prompt so it displays the working directory. export PS1="\w \$".

The prompt displays correctly, however, the symbol \$ does not transform into a #, even though my $UID is 0, which kind of defeats the purpose of omitting the user symbol \u. Is there something extra I have to add, or does that symbol not work if I export it?

dook
  • 1,213
  • 1
  • 13
  • 30

3 Answers3

18
export PS1="\w \$"

This doesn't set $PS1 to \w \$, it sets it to \w $, as you can see if you type:

echo "$PS1"

Use single quotes:

export PS1='\w \$'
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Thank you, I can't believe the solution was so simple! How come "\w" parsed correctly, though? Almost every single symbol (\u, \h, even the color prompts [\033...) worked correctly for me inside of the PS1 prompt. – dook May 01 '14 at 19:02
  • @bark: Probably because `$` is a special character within double quotes, so `"\$"` escapes the `$` so it's a literal `$` character. I'm not sure about all the details, but that seems like a plausible explanation. – Keith Thompson May 01 '14 at 19:04
  • 1
    In scripts, the `'` quote does not get parsed/expanded: its value is dumped straight into the variable. The `"` quote DOES get parsed/expanded, so spaces get expanded to `\ `, `\n` gets expanded to a newline, etc. Since `\w` does not have a "special" meaning, the `\` was actually expanded to `\\` to make `\\w`, which was assigned to the variable as a literal `\w`. The `\$` does have a "special" meaning, so it became a literal `$`. – OnlineCop May 01 '14 at 21:58
  • @OnlineCop: `\n` *isn't* expanded to a newline in bash double-quoted strings. You can use `$'...'` to get something resembling C expansion rules. (BTW, I think the mix of backticks and backslahes messed up some of the content in your comment.) – Keith Thompson May 01 '14 at 22:05
  • @KeithThompson: `echo -e "Hello\nworld"` ;) – OnlineCop May 01 '14 at 22:17
  • @OnlineCop: That's expanded by `echo -e`, not by the shell. (Well, `echo` is a shell builtin, but `/bin/echo` does the same thing.) And the `\n` sequence is also recognized in `$PS1`. – Keith Thompson May 01 '14 at 22:18
  • this is better (double escape): export PS1="\w \\$" – Michael A. Jun 03 '19 at 09:09
  • @MichaelA. It's equivalent, and if you prefer it that's fine, but I don't see how it's better. – Keith Thompson Jul 28 '21 at 15:52
2

the slash will be gone in the "". Just need to add one more to keep it. Either

export PS1='\w \$'

or

export PS1="\w \\$"

works for you.

You can combine '' and "". For example:

export PS1="\w blabla"'\$'
wuxb
  • 2,572
  • 1
  • 21
  • 30
1

You could use this:

export PS1="\w \\$"

I don't know why it works. But it works.I have originally seen this here: cyberciti