Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash Prompt With Exit Code of Last Command
# Set a Bash prompt that includes the exit code of the last executed command.
#
# Setup: paste the content of this file to ~/.bashrc, or source this file from
# ~/.bashrc (make sure ~/.bashrc is sourced by ~/.bash_profile or ~/.profile)
#
# Daniel Weibel <danielmweibel@gmail.com> October 2015
#------------------------------------------------------------------------------#
# Command that Bash executes just before displaying a prompt
export PROMPT_COMMAND=set_prompt
set_prompt() {
# Capture exit code of last command
local ex=$?
#----------------------------------------------------------------------------#
# Bash text colour specification: \e[<STYLE>;<COLOUR>m
# (Note: \e = \033 (oct) = \x1b (hex) = 27 (dec) = "Escape")
# Styles: 0=normal, 1=bold, 2=dimmed, 4=underlined, 7=highlighted
# Colours: 31=red, 32=green, 33=yellow, 34=blue, 35=purple, 36=cyan, 37=white
#----------------------------------------------------------------------------#
local color='\e[1;32m'
local reset='\e[0m'
# Set prompt content
PS1="\u@\h:\w$\[$reset\] "
# If exit code of last command is non-zero, prepend this code to the prompt
[[ "$ex" -ne 0 ]] && PS1="$ex|$PS1"
# Set colour of prompt
PS1="\[$color\]$PS1"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.