I want my prompt to be changed based on an output of a certain command. and based on the command result to add a color.

run the command:

cphaprob stat | grep local | awk '{ print $NF }'`

(this will show the last word only.

Now, if the result is "attention", I want the prompt to be:

PS1='[\t][\u@\h]\[\e[0;92m\][attention]\[\e[0m\]# '  

so the word "attention" will be green.

However if the word will be "down" I want the prompt to be in different color:

PS1='[\t][\u@\h]\[\e[4;91m\][Down]\[\e[0m\]# '

I want the change to be "on-the-fly" meaning on each new line (pressing Enter) I want the prompt to be updated based on the result.

If possible this should somehow be made permanent via .bashrc.

Any ideas on how to make it work ?


This works for me (using bash 4.2.37):

PS1='[\t][\u@\h][$(i=$(cphaprob stat|grep local|awk "{print \$NF}")
case $i in
(Active|attention) c=92;;
(Down|Error) u=4; c=91;;
(Standby) c=93;;
(Ready) c=94;;
(*) c=95 ;;
printf "\033[%s;%sm%s\033[0m" $u $c $i
)]# '
  • Are "attention" and "Down" the only possible values? – jlliagre Apr 16 '14 at 19:55
  • So what colors are you expecting for the other values ? – jlliagre Apr 16 '14 at 20:05
  • Answer updated. – jlliagre Apr 16 '14 at 20:25
  • Answer updated again and made simpler. You should put that code as is in your .bashrc meaning you shouldn't double the backslash in \$NF. – jlliagre Apr 16 '14 at 21:02
  • Hi, If I'm not putting the double backslash I'm getting syntax error. is there a way to chat here? i need few explenations. thanks – AlonCo Apr 16 '14 at 21:37

You'll need to leverage the PROMPT_COMMAND variable as well as the PS1 variable, redefining the PS1 variable inside PROMPT_COMMAND. I'll let you reference other answers for specifics on how to accomplish your specific need, but this will resolve the request to update "on-the-fly." This was a challenge I ran into when working through including the exit status in each new prompt (if non-zero).

For example, my bash config files 'build' a PS1 prompt, which is subsequently set using the following command (where variable ps1 represents what I want my PS1 variable to be):

export PROMPT_COMMAND="export PS1=\"$ps1\""

Here's my full .bash_prompt file for your reference (which I simply include from .bashrc): https://gist.github.com/austinbeam/10930268

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.