4

I want my bash prompt to change depending on external conditions.

Here is excerpt from the bash manual:

PROMPT_COMMAND: If set, the value is executed as a command prior to issuing each primary prompt.

PS1: The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt string.

In my .bash_profile I have following:

export PROMPT_COMMAND="echo -n ┏━━━[$(date +%H:%M)]"
export PS1="━━[\t]━━━┓\n\$ "

Here is what I see in terminal:

┏━━━[03:46]━━[03:46:52]━━━┓
$ cd ..
┏━━━[03:46]━━[03:51:37]━━━┓
$

As you can see, PROMPT_COMMAND doesn't get executed more than once, and remains static forever.

How can I have it executed "prior to issuing each prompt", as stated in the manual?

I'm running Mac OS X 10.9.3
echo $BASH_VERSION
3.2.51(1)-release

2

The PROMPT_COMMAND gets run every time, but the $(...) snippet is only evaluated when your .bash_profile is loaded. This is because the double quotes mean to still expand variables and commands.

If you use single quotes, the command is not substituted during the execution of .bash_profile, it is evaluated when the PROMPT_COMMAND is run.

  • Thank you. This works as expected: export PROMPT_COMMAND='echo -n "┏━━━[$(date +%H:%M)]"' – Sergei May 28 '14 at 2:10
  • 2
    I just discovered that it is possible to evaluate code in the PS1 as well PS1="[\$(date +%H:%M)] \u@\w\ $ ". It makes PROMPT_COMMAND superfluous. – Sergei May 28 '14 at 22:43
  • @Sergei That's awesome, I'm going to use that. But for what you're doing (since it's the line above) I'd recommend using PROMPT_COMMAND. – 0942v8653 May 28 '14 at 22:48
3

Your date call got evaluated when you set PROMPT_COMMAND so it is forever stuck at the time that you ran:

export PROMPT_COMMAND="echo -n ┏━━━[$(date +%H:%M)]"

Try defining a function instead and assigning that to PROMPT_COMMAND:

function prompt_command() {
    PS1="┏━━━[$(date +%H:%M)]━━[\t]━━━┓\n\$ "
}
export PROMPT_COMMAND=prompt_command

You can also use \@ for the current time in 12-hour AM/PM format in your prompt. So:

function prompt_command() {
    PS1="┏━━━[\@]━━[\t]━━━┓\n\$ "
}
export PROMPT_COMMAND=prompt_command

Would give you:

┏━━━[06:17 PM]━━[18:17:57]━━━┓
$

And while we're talking bash customizations let me put in a plug for the excellent bash-it project -- it's a bash equivalent to oh-my-zsh and it comes with a bunch of helper functions for theme creation. You might find it makes this sort of thing a little easier.

  • Thank you! You answer is very useful (the function is a great idea indeed!), but I accepted the first one, because it clearly explains what's going on from the technical standpoint. bash-it is a goldmine. – Sergei May 28 '14 at 2:07
  • @Sergei no worries. That's how it works around here. You should pick the answer you think best represents the solution to your posed question! – Ian C. May 28 '14 at 16:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .