Skip to content

Instantly share code, notes, and snippets.

@nebrelbug
Last active November 28, 2019 04:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebrelbug/32f31e921143ea6fd5b8e16cea80312c to your computer and use it in GitHub Desktop.
Save nebrelbug/32f31e921143ea6fd5b8e16cea80312c to your computer and use it in GitHub Desktop.
NiftyBash: customize terminal prompt to show package.json version, git branch, and commit status (this is the end of my `.bashrc`)
COLOR_RED="\033[0;31m"
COLOR_YELLOW="\033[0;33m"
COLOR_GREEN="\033[0;32m"
COLOR_OCHRE="\033[38;5;95m"
COLOR_BLUE="\033[0;34m"
COLOR_WHITE="\033[0;37m"
COLOR_RESET="\033[0m"
function git_color() {
local git_status="$(git status 2>/dev/null)"
if [[ ! $git_status =~ "working directory clean" ]]; then
echo -e $COLOR_GREEN
elif [[ $git_status =~ "Your branch is ahead of" ]]; then
echo -e $COLOR_YELLOW
elif [[ $git_status =~ "nothing to commit" ]]; then
echo -e $COLOR_GREEN
else
echo -e $COLOR_OCHRE
fi
}
function git_branch() {
local git_status="$(git status 2>/dev/null)"
local on_branch="On branch ([^${IFS}]*)"
local on_commit="HEAD detached at ([^${IFS}]*)"
if [[ $git_status =~ $on_branch ]]; then
local branch=${BASH_REMATCH[1]}
echo "($branch)"
elif [[ $git_status =~ $on_commit ]]; then
local commit=${BASH_REMATCH[1]}
echo "($commit)"
fi
}
function npm_version() {
if [ -f "package.json" ]; then
# Version key/value should be on his own line
PACKAGE_VERSION=$(cat package.json |
grep version |
head -1 |
awk -F: '{ print $2 }' |
sed 's/[",]//g' |
tr -d '[[:space:]]')
if [[ -n "$PACKAGE_VERSION" ]]; then
# String exists
echo "@$PACKAGE_VERSION"
fi
fi
}
PS1="${debian_chroot:+($debian_chroot)}"
PS1+="\[$COLOR_GREEN\]\u@\h\[$COLOR_WHITE\]:\[$COLOR_BLUE\]\w" # basename of pwd
PS1+="\[$COLOR_YELLOW\]\$(npm_version)"
PS1+="\[\$(git_color)\]" # colors git status
PS1+=" \$(git_branch)" # prints current branch
PS1+="\n\[$COLOR_GREEN\]λ\[$COLOR_RESET\] "
# If this is an xterm set the title to user@host:dir (not really sure what this does)
case "$TERM" in
xterm* | rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*) ;;
esac
export PS1

Features

  • NPM Package version
  • Git status
  • Git branch
  • Cool lambda symbol

Screenshot

TerminalScreenshot

Instructions

Paste at the end of your .bashrc

Feel free to fork or request changes!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment