0

This question already has an answer here:

When setting the value of the primary command prompt (PS1) the followig two cases

export PS1="\u"
export PS1="\\u"

gives the same result:

root

as a command prompt string. How does the \u and \\u differs if the both results is identical? Shouldn't the \\u outputs just \u since \\ denotes backslash itself?

marked as duplicate by grawity bash Jan 11 '18 at 10:50

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Command prompt is a Microsoft term. Are you actually referring to Terminal instead? – LPChip Jan 10 '18 at 18:59
  • 1
    I'm just referring to bash prompt controlled by the PS1 variable. – Ringger81 Jan 10 '18 at 19:13
1

In bash's double-quoted strings, backslashes are preserved if the following character does not need escaping (only " ` $ \ must be escaped).

  • For example, foo="\$bar" will result in $bar because $ needs to be escaped.
  • However, foo="\%bar" will result in \%bar because % does not need to be escaped.

So both PS1="\u" and PS1="\\u" will result in $PS1 having the value \u.


The code \u inside $PS1 is expanded to your username much later – not when assigning the variable, but every time when the prompt is shown.

  • So the the sequece is like so: – Ringger81 Jan 11 '18 at 10:02
  • @gravity So the algorithm is - bash takes the first char and checks the next one. In the \u case it checks that u is just a normal char that need not to be escaped and so preserves the backslash resulting in\u. In the \\u case bash takes the second char which is now another backslash so it escapes it resulting in only one backslash from two. After that there is now \u and the same treatment is applied as in the first \u case described earlier. Is my explanation right? – Ringger81 Jan 11 '18 at 10:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.