1

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?

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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