Monday, 4 April 2011

Bash, PS1, PROMPT_COMMAND and other fun

I've just spent 30 mins trying to understand the flow between the various files that set a bash prompt on fedora to do the following: (assumption is here that you're in a colour xterm)

I want:
* my username to change colour depending if I still have a valid kerberos token
* the hostname of the machine I'm on to be in RED if I'm root
* displayed path to be as simple as possible
* $ if I'm a minion, # if root as mormal
* command line editing to work sensibly, no wierdisms on wrapping long lines

so - I used to have on my machine something like the following:
if [ "$PS1" != "" ] ; then
klist -s
if [ $? -eq 0 ] ; then
PS1='\[\033[32m\]\u@\h\[\033[0m\]:\w\$ '
else
PS1='\[\033[36m\]\u\[\033[32m\]@\h\[\033[0m\]:\w\$ '
fi
fi

and something similar for root.

But on my laptop (F14) I wanted it system wide, so went down the approach of customising /etc/bashrc where you find calls to
PROMPT_COMMAND=/etc/sysconfig/bash-prompt-xterm

1) /etc/sysconfig/bash-prompt-* aren't included, so you're on your own
2) It must point to an executable script that is run every time before displaying the prompt
3) PS1 is still displayed *AND* if you use tab completion / ctrl-l, its *only* PS1 thats displayed on your screen, not the output from PROMPT_COMMAND

so: DON'T do the following:

cat /etc/sysconfig/bash-prompt-xterm
#!/usr/bin/env bash
# set green username if we have a valid kerberos token, else cyan
klist -s
if [ $? -eq 0 ] ; then
K='[32m'
else
K='[36m'
fi
# set hostname in red if we're root, green otherwise
if [ ${USER} = 'root' ] ; then
U='[31m'
else
U='[32m'
fi

printf "^[%s%s^[[37m@^[%s%s^[[0m:%s " ${K} ${USER} ${U} ${HOSTNAME%%.*} "${PWD/#$HOME/~}"
#echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\007"
(where ^[ is 'ctrl-v, esc' in vim)
because you end up with stuff like

aelwell@pcitgtelwell:~[aelwell@pcitgtelwell ~]$

until you press ctrl-l and end up with just
[aelwell@pcitgtelwell ~]$ (ie, $PS1)


but *DO* make the call to see if you have a valid token and set the xterm titlebar in /etc/sysconfig/bash-prompt-xterm, but if you're altering PS1, then do so in the traditional places of /etc/bashrc and (as suggested in that file) a custom modification shell script in /etc/profile.d/ directory.

Ho Hum. Hope this clears up for anyone else trying to work out what the sysconfig/bash-prompt-* files do.

oh, and does anyone know a lighter call to see if a token is still valid than 'klist -s'?

No comments:

Word of mouth Skye History

Many years ago we lived in the Old Manse in Waternish, Skye. If you look on the maps, you'll spot that unlike nearly all the other house...