0

Say I want to include an escape sequence dynamically:

if [ -n $something ]; then
    user="\u"
else
    user="admin"
fi
PS1='$user@\h$ '

The problem is, instead of filling in the user name, my prompt looks like this:

\u@ubuntu-1$ 

Even if I escape the backslash (user="\\u") it still does not print out the user name. How do I get the prompt to look like this:

andreas@ubuntu-1$ 
IQAndreas
  • 8,060
  • 8
  • 39
  • 74
  • What exactly do you want your prompt to look like? – merlin2011 May 23 '14 at 02:12
  • What version of bash do you use? I've just checked your example and it does work as expected (BASH_VERSION=`bash-3.2.51(1)-release`). – user3159253 May 23 '14 at 02:13
  • @merlin2011 I want my prompt to look like the final example I gave: `andreas@ubuntu-1$ ` – IQAndreas May 23 '14 at 02:27
  • @user3159253 Found the problem, the example I gave uses double quotes, [the assignment in my `.bashrc` file](https://gist.github.com/IQAndreas/ed12b30977acc529163c) uses single quotes. The example has been updated with this new information. – IQAndreas May 23 '14 at 02:40
  • Why not use double quotes? You need them for variable interpolation to work. – merlin2011 May 23 '14 at 02:57
  • @merlin2011 Add that as an answer. The single quotes were already there in `.bashrc` by default; are they actually required to be single quotes (looking at the rest of my "default `PS1` contents"), or can I switch over to double quotes without issues? – IQAndreas May 23 '14 at 02:59
  • 1
    You can use either type of quotes, depending on your need. Single quotes are often used to delay expansion until `PS1` is actually displayed, for example, `PS1='$(date) '` to display the current date, rather than the date when `PS1` was defined. – chepner May 23 '14 at 03:04
  • @IQAndreas, If you are still having problems I have updated the answer with another option. – merlin2011 May 23 '14 at 03:51

1 Answers1

1

Use double quotes when you are trying to interpolate variables and want them to expand.

You also have another option, instead of dealing with \u and complications with when the interpretation of it happens.

if [ -n $something ]; then
    user=`whoami`
else
    user="admin"
fi
PS1="$user@\h$ "
merlin2011
  • 71,677
  • 44
  • 195
  • 329