0

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?

Ringger81
  • 1,097
  • 3
  • 11
  • 22

1 Answers1

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.

u1686_grawity
  • 426,297
  • 64
  • 894
  • 966
  • 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