Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I am using this function:

function test(){
  local var="hello"
  PS1="\u\$$var"
}

The output I am trying to get from the function is john$hello.

But what I get is just john.

If I add a space before $var, then I do get close to what I want - but I do not want the space in there.

Is it possible to do what I want without having that space?

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Since you've used double quotes when setting PS1, the variable substitution is evaluated at the point where you assign to the variable. So you've ended up setting PS1 to \u$hello. The shell expands variables before displaying the prompt, and since you don't have any variable called hello, that part of the prompt expands to the empty string.

If you set PS1 using single quotes, the variable substitution will not be performed at that point. This will cause the $var part to be evaluated when the prompt is shown though, which means it won't pick up the local variable you've defined in your shell function.

The third option that should work with a local variable from a shell function is to escape the meta-characters:

PS1="\u\\\$$var"

This should result in PS1 being set to \u\$hello. The end of the prompt will not change when the variable var changes in this case.

share|improve this answer
    
Beautiful explanation. Thank you! –  Zabba Oct 24 '11 at 4:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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