Monday, 21 December 2009

The Ultimate zsh Prompt

I cram a lot of information into my zsh prompt. I could describe it, but a picture covers it better:



The code behind this, to be stuffed in your $HOME/.zshrc, is:


autoload colors
colors

precmd()
{

PREV_RET_VAL=$?

if [ "$TERM" = "dumb" ]
then
PS1="%n@%m %% "
return
fi

if [ $EUID -eq 0 ]
then
USER_COLOUR=red
else
USER_COLOUR=green
fi

BASIC_COLOUR=cyan

# Basic prompt: 'user@host [history-number'"
PS1="%{${fg[$USER_COLOUR]}%}%n@%m %{${fg_bold[$BASIC_COLOUR]}%}%1~%{${fg[$BASIC_COLOUR]}%} [%!"

# Possibly append '/job-count', if the number of jobs is > 0
if [ $#jobstates -ne 0 ]; then
PS1="${PS1}/%j"
fi

# Possibly append '/error-status', if $? wasn't 0
if [ $PREV_RET_VAL -ne 0 ]
then
PS1="${PS1}/%{${fg_bold[red]}%}$PREV_RET_VAL%{${fg_bold[$BASIC_COLOUR]}%}"
fi

# Close off the brackets for the status section, and finalise.
PS1="${PS1}] %% %{${fg_no_bold[default]}%}"
}


This uses only shell built-ins, so is suitably fast for running at every prompt.

One variant I used at work was to colour the prompt based on the DEPLOYMENT_STATUS environment variables that the SAs set (one of 'prod', 'test', 'dev', 'cont'): red for production, purple for contingency, blue for test, and green for development, but that's not quite as useful at home. :-)

No comments:

Post a Comment