Last Updated: September 09, 2019
·
4.266K
· lukaszkorecki

Show last command's status in bash prompt

If a command fails it most of the times gives you an error message. More often it will also exit with non-zero status code, which can be inspected with $?.

The real problem is that some applications will fail silently (that being due to laziness of the author or weird logging setup).

I've created a handy little helper for Bash (which can also be adopted to work with ZSH) which shows a tick if last command was successful or not:


#!/usr/bin/env bash
# helper functions for Bash - easier coloring than using escape sequences
function Color() {
  echo "\[$(tput setaf $1)\]"
}
function ResetColor() {
  echo "\[$(tput sgr0)\]"
}


# now you can add it to your prompt like this:
# function which configures the prompet...
function BashPrompt() {
    local last_status=$?
    local reset=$(ResetColor)

    local failure="✘"
    local success="✔"

    if [[ "$last_status" != "0" ]]; then
        last_status="$(Color 5)$failure$reset"
    else
        last_status="$(Color 2)$success$reset"
    fi

    # ...some other things like hostname, current git branch etc

    echo "$last_status $current_branch $hostname :"
}

# ...and the hook which updates the prompt whenever we run a command
PROMPT_COMMAND='PS1=$(BashPrompt)'

Here's how it looks like on my machine:

Picture

1 Response
Add your response

Should I add this in ~/.bashrc or ~/.bash_profile?

over 1 year ago ·