Skip to content

Instantly share code, notes, and snippets.

@danielschwartz85
Last active March 25, 2024 13:03
Show Gist options
  • Save danielschwartz85/6bb200e24ea7f5c5fd224a85f3789292 to your computer and use it in GitHub Desktop.
Save danielschwartz85/6bb200e24ea7f5c5fd224a85f3789292 to your computer and use it in GitHub Desktop.
Customize bash prompt with time, node version and branch

Customize bash prompt with time, node version and branch

~/.bashrc

function setps1()
{
    NODE=`node -v | grep -Po 'v\K\d+'`
    BRANCH=`git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`
    CHANGES=`git status 2> /dev/null | (grep -q changes 2> /dev/null && echo "")`
    STAGED=`git status 2> /dev/null | (grep -q 'Changes to be committed' 2> /dev/null && echo "")`
  
    # todo: takout PS1 prefix, or use STATUS var for git status. 
    if [ ! -n "${BRANCH}" ]; then
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\t [n $NODE] \[\033[01;34m\]\w\[\033[00m\] $ '
    else
      if [ ! -z "$CHANGES" ]; then
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\t [n $NODE] \[\033[00m\]\[\033[01;34m\]\w\[\033[00m\] \[\033[0;33m\]($BRANCH)\[\033[00m\]\[\033[00;31m\] $CHANGES  \[\033[00m\]$ '
      elif [ ! -z "$STAGED" ]; then
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\t [n $NODE] \[\033[00m\]\[\033[01;34m\]\w\[\033[00m\] \[\033[0;33m\]($BRANCH)\[\033[00m\]\[\033[00;35m\] $STAGED  \[\033[00m\]$ '
      else
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\t [n $NODE] \[\033[00m\]\[\033[01;34m\]\w\[\033[00m\] \[\033[0;33m\]($BRANCH)\[\033[00m\]\[\033[01;32m\] ✔  \[\033[00m\]$ '
      fi
    fi
}

PROMPT_COMMAND=setps1  # call this funcion every new prompt (sets PS1 var).

Should look something like (with colors)
16:02:18 [n 18] ~/dev/kep-ve-management/ve-management (master) ✔

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