Bash Tricks I Like #3

Keep track of your branches.

One may want to access the current git branch via bash for a variety of reasons. One common reason is to include the git branch name in your prompt. For that, I would recommend using the git-prompt.sh script provided in the git source repository. Another way one may use the current git branch name (and the way that I personally do), is to display it in the tmux status bar.

The bash script below provides the current git branch in the variable GIT_BRANCH. The variables is updated every time the prompt changes (so every time that you change directories).

get_git_branch() {
  if [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" ]; then
    local branch short_branch
    branch=$(git symbolic-ref -q HEAD)
    branch=${branch##refs/heads/}
    branch=${branch:-HEAD}
    short_branch=$(echo "$branch" | cut -c1-20)
    if [ ${#branch} -gt ${#short_branch} ]; then
      short_branch=${short_branch}...
    fi
    GIT_BRANCH=$short_branch
  else
    GIT_BRANCH=
  fi
}

PROMPT_COMMAND="get_git_branch; $PROMPT_COMMAND"

The code contains both a branch and a short_branch. The short branch is simply a truncated version of branch, that uses the cut command to limit the branch name to 20 characters with a trailing ellipsis if applicable. This behaviour can be modified or removed entirely.

Enjoy your new ability to access the current git branch name at all times. Leave a comment saying how you make use of it.