Camilo Martin
Camilo Martin

Reputation: 37908

How to set a variable from the bash $PS1

The bash PS1 variable seemingly has access to all the shell's variables.

$ foo=bar
$ PS1='$foo '
bar # Works as expected.

But, setting a variable there does not work.

$ PS1='$(bar=baz)\$ '
$ echo $bar

$ # Does not work.

Why, and how to make this work?

Upvotes: 1

Views: 3958

Answers (1)

Camilo Martin
Camilo Martin

Reputation: 37908

Why:

The PS1 variable is evaluated as a string. In a bash string, you can do this:

$ myString="$foo"

And this:

$ myString="Date: $(date)"

But not this:

$ myString="$(foo=bar)"

The PS1 variable is simply not exempt from this rule.

Note: as mkelement0 explains in the comments, this is because the foo=bar part will be executed in a subshell, so you could do $(foo=bar;echo $foo), though - it's just that the variable will only exist in that scope.

How to make this work:

There's another variable, called PROMPT_COMMAND. The code here will be eval()'d at each prompt string, before the evaluation of the PS1 variable.

Thus, even just writing your assignment here as-is will work:

$ PROMPT_COMMAND='bar=baz'
$ echo $bar
baz # Works!

Remember to check if you're not overwriting previously-set contents in the PROMPT_COMMAND that you may want to keep, though.

Upvotes: 2

Related Questions