Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question is very similar to this one: Colored PS1 string

But I still don't understand completely.

So say I have this function

function getjobs {
    echo $(jobs | wc -l)

And my PS1 is this

PS1="\u@\h: [jobs "
PS1="$PS1\$(if [[ $(getjobs) == 0 ]] ; then
               echo $(color $green);
               echo $(color $red);

Now this only gets evaluated when .bashrc is loaded for the first time but what I want to have happen is this if statement evaluated every time a new prompt appears.

How can I do this?

EDIT: the color function returns escape sequences for those colors.

share|improve this question
up vote 0 down vote accepted

I usually use something like this:

    if [[ ]]; then
      echo -n "something"
      echo -n "something else"

export PS1="\$(method_that_echoes_values)"

Note that getting it extracted to a method is required

share|improve this answer
When I did this, it printed out the escape sequence literally, I added a -e and that fixed that. Thanks! – adamk33n3r Mar 8 '13 at 5:43
One thing actually. Because I am using functions to format, the $? variable is getting set to the return value of those functions and my return value indicator is no longer functioning correctly. Is there some way I can store the old $? before my calls? – adamk33n3r Mar 8 '13 at 5:59

I would use bash's PROMPT_COMMAND for this. See the bash man page and this answer for an example.

share|improve this answer
What's the difference? – adamk33n3r Mar 8 '13 at 7:23
I find it easier to set PS1 explicitly in a function invoked through PROMPT_COMMAND than to figure what I have to echo and how to get the quoting right when setting PS1 to the output of a function. I don't know of any other difference. – garyjohn Mar 8 '13 at 7:51
I suppose that makes sense. I'll look into it. Thank you for your knowledge – adamk33n3r Mar 8 '13 at 18:50

So I was doing more experimenting with different placement of different quotes and I found something that works, but if someone knows a cleaner, better solution, please let me know.

PS1="\u@\h: [jobs "
PS1="$PS1\$(if [[ "'$(getjobs)'" == 0 ]] ; then
           echo $(color $green);
           echo $(color $red);

All I had to do was put the part that I want reevaluated in single quotes with everything else in double quotes. I didn't think that it'd work since I had a double quoted string next to a single quoted string but I guess that's an ok thing.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.