Saturday, August 30, 2014

Complex prompts in bash

I've been using a a bash script to generate my prompts for quite a while though I didn't realize that it wasn't working in normal shells (anything besides Emacs).

The flawed setup is as follows:

.bashrc
export PROMPT_COMMAND="my_custom_bash_prompt_script"
export PS1=""

This setup works fine from within an Emacs shell but from a "normal" shell, when I did an up arrow, the prompt itself would disappear!

The corrected setup is very similar:

.bashrc
function bash_command_function {
  PS1=`my_custom_bash_prompt_script`
}
export PROMPT_COMMAND="bash_prompt_script"

Once I realized that I needed a bash function anyways (because you can't export something from a subshell to the super shell), I just inlined my rather simple script.

Keep in mind, if my_custom_bash_prompt_script ever returns anything with a % character in it, bash may interpret it, so you will need to escape the %s.