Joshua Cheek
Joshua Cheek

Reputation: 31786

How to generate PS1 in a function (escaping issues)

I'd like to move my bash prompt's construction into a function that can build it up modularly. The problem is that I cannot figure out how to get the function's result to be interpreted.

Example:

function build_prompt {
  echo "\@"
}
export PS1="\$(build_prompt)"

My prompt always shows as \@, but should be the current time.

Sure there are ways around this particular example, but I'd like a general solution so I can use it for other escaped components, such as colours.

Upvotes: 0

Views: 187

Answers (1)

chepner
chepner

Reputation: 532323

This is one use case for the PROMPT_COMMAND variable: running a function just before displaying the prompt that updates the value of PS1.

function build_prompt {
    PS1='\@'
}
PROMPT_COMMAND='build_prompt'

Upvotes: 1

Related Questions