I had most of this functionality accomplished in BASH, but I was having trouble getting the last process's return value (even though I had a minimal working example). Plus, the escape codes made everything unreadable and I wasn't sure how to factor them out appropriately.
Since I know Python pretty well, I decided to rewrite it in Python, since I have now figured out enough shell that I felt confident embedding some Python into it.
The __future__
import should allow this to work in Python 2 or 3.
I do not know if this is cross-compatible with other shells, or if this is only likely to work in BASH, but another driver that pushed me in this direction was that desire. I am aware of the PROMPT_COMMAND for BASH.
Perhaps I could use a similar technique along with a BASH function to keep it all in shell and avoid the Python process altogether. However, I find this to be incredibly easy to read, work on, and modify without fear of breaking it - especially relative to shell scripting.
Another perhaps: maybe these escape codes are already available in the Python standard library. I looked at ncurses - I don't think that's the one I want to focus on.
I'm not sure if I factored the escape codes properly - perhaps I should have the constants point to the formatted escapes instead. But theoretically I could embed multiple codes into a single escape, instead of doing it multiple times for every tweak. Maybe there's a drawback to doing that my way, too.
PS1="\$(export LAST_RETURN_VALUE="\$?" WHOAMI="\$\(whoami\)" HOSTNAME ; python -c \"
from __future__ import print_function
import os
import datetime
ESC = '\033[{0}m'
esc = ESC.format
OFF, BOLD, UNDERSCORE, BLINK = 0, 1, 4, 5
BLACK, BLACKBG = 30, 40
RED, REDBG = 31, 41
GREEN, GREENBG = 32, 42
YELLOW, YELLOWBG = 33, 43
BLUE, BLUEBG = 34, 44
MAGENTA, MAGENTABG = 35, 45
CYAN, CYANBG = 36, 46
WHITE, WHITEBG = 37, 47
LAST_RET = os.environ['LAST_RETURN_VALUE']
print(esc(YELLOW) + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
esc(GREEN) + os.environ['WHOAMI'] + esc(RED) + '@' +
esc(CYAN) + os.environ['HOSTNAME'],
esc(BLUE) + esc(BOLD) + os.getcwd() +
esc(OFF))
if LAST_RET != '0':
print(esc(MAGENTABG) + LAST_RET + esc(OFF), end='')
print('$ ', end='')
\" "
I'm getting impatient and want to go ahead and post this. I usually do more due diligence on code I write, but I'm up way past my bedtime already, and I think this is too clever not to share.
Here's the result: