Efficient way to colorize text in a bash prompt without two calls?
There are many resources around setting up your PS1. The critical points are here:
- You can call a custom function to generate text, resulting in custom text
- It is possible that such a function produces custom color codes.
- Non-printable text (such as color codes) must be marked to do word wrapping work.
- Cannot perform this marking with a custom function.
Perhaps I am mistaken at the last point, and if there is a way, this will perfectly solve this.
Here's a simplified and somewhat far-fetched example that is topologically similar, if that makes sense, to the one I'm messing with. I have an external command (call it generate_text ) that gives stdout either "OK" or some kind of one-word message. It may also not emit anything at all. These three states should appear in the tooltip: if it does not emit anything, leave the tooltip exactly as it is ( user@hostname :path$ ); if it emits OK, put a green “OK” before the invitation; if something else, put this text in red.
My current solution is to create a custom function that calls generate_text and either emits its text or emits a color code on it and then calls this function twice:
generate_prompt() { txt=`generate_text` [ -z "$txt" ] && exit
This means that I have to call generate_text twice and assume that they will return the same string (which will usually be the case, but it is theoretically possible that the state can change between two calls). It seems wasteful to me. Is there a convenient way to emit both a non-printable color code and part of the text from the same function?
source share