Skip to content

Instantly share code, notes, and snippets.

@murtaza-u
Created December 18, 2022 19:33
Show Gist options
  • Save murtaza-u/9df893ebaf30c63752a6a9e4eee2e346 to your computer and use it in GitHub Desktop.
Save murtaza-u/9df893ebaf30c63752a6a9e4eee2e346 to your computer and use it in GitHub Desktop.
Custom bash prompt with Git information
#!/bin/bash
# Add everything below to your .bashrc
multiline_prompt=0
hostinfo=0
__ps1() {
# colors
local red='\[\e[1;31m\]'
local green='\[\e[1;32m\]'
local yellow='\[\e[1;33m\]'
local blue='\[\e[1;34m\]'
local magenta='\[\e[1;35m\]'
local cyan='\[\e[1;36m\]'
local white='\[\e[37m\]'
local reset='\[\e[0m\]'
local git_status="$(git status 2> /dev/null)"
local branch_pattern="^(# )?On branch ([^${IFS}]*)"
if [[ ${git_status} =~ ${branch_pattern} ]]; then
local branch=${BASH_REMATCH[2]}
fi
local hash_pattern="^(# )?HEAD detached at ([^${IFS}]*)"
if [[ ${git_status} =~ ${hash_pattern} ]]; then
local hash=${BASH_REMATCH[2]}
fi
local modified_pattern="modified:"
if [[ ${git_status} =~ ${modified_pattern} ]]; then
local modified_symbol="!"
fi
local deleted_pattern="deleted:"
if [[ ${git_status} =~ ${deleted_pattern} ]]; then
local deleted_symbol="✘"
fi
local untracked_pattern="Untracked files:"
if [[ ${git_status} =~ ${untracked_pattern} ]]; then
local untracked_symbol="?"
fi
if [[ -n "$deleted_symbol" ]] ||
[[ -n "$modified_symbol" ]] ||
[[ -n "$untracked_symbol" ]]; then
local symbols="$(printf "[%s%s%s]" "$deleted_symbol" "$modified_symbol" "$untracked_symbol")"
fi
if [[ -n "$git_status" ]]; then
local gitinfo="$reset:$yellow$branch$hash$red$symbols$reset"
fi
if [[ "$hostinfo" -ne 0 ]]; then
local host="$red\u$reset@$blue\h$reset:"
fi
local prompt="$host$cyan\W$gitinfo$reset"
if [[ "$multiline_prompt" -ne 0 ]]; then
PS1="╔ $prompt\n╚ \$ "
else
PS1="$prompt\$ "
fi
}
PROMPT_COMMAND='__ps1'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment