0

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);
            else
               echo $(color $red);
            fi)"

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.

0

I usually use something like this:

method_that_echos_values(){
    if [[ ]]; then
      echo -n "something"
    else
      echo -n "something else"
    fi
}

export PS1="\$(method_that_echoes_values)"

Note that getting it extracted to a method is required

  • When I did this, it printed out the escape sequence literally, I added a -e and that fixed that. Thanks! – Adam Keenan 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? – Adam Keenan Mar 8 '13 at 5:59
1

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

  • What's the difference? – Adam Keenan 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 – Adam Keenan Mar 8 '13 at 18:50
0

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);
        else
           echo $(color $red);
        fi)"

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.

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.