Skip to content

Instantly share code, notes, and snippets.

@ByScripts
Last active October 9, 2015 07:37
Show Gist options
  • Select an option

  • Save ByScripts/3462873 to your computer and use it in GitHub Desktop.

Select an option

Save ByScripts/3462873 to your computer and use it in GitHub Desktop.
Bash and Zsh prompt with Git support
# To use, download this file at the root of your home directory, than add :
# . .bash_git.sh
# at the end of you .bashrc file
# Colors
LineColor="\e[0;36m"
GitNotOkColor="\e[1;31m"
GitOkColor="\e[1;32m"
RootLineColor=$GitNotOkColor
WorkingDirColor="\e[0;93m"
TimeColor="\e[0;96m"
# Get the current working dir "home-shortened" (~/dir instead of /home/user/dir)
function getShortWorkingDirectory {
escaped_home=$(echo $HOME | sed -e 's/[\/&]/\\&/g')
short_working_directory=$(pwd | sed -e "s/$escaped_home/~/g")
echo $short_working_directory
}
# Get the current Git branch without parenthesis
function getGitBranch {
echo $(__git_ps1 "%s")
}
# Get the current Git status
# ok = Current Git branch is clean
# nok = Current Git branch is dirty
# notgit = Not in a git repository
function getGitStatus {
if [[ $(getGitBranch) != "" ]]; then
git status | grep "nothing to commit" > /dev/null 2>&1
if [[ $? -eq 0 ]]; then
echo "ok"
else
echo "nok"
fi
else
echo "nogit"
fi
}
# Build the prompt
function gitPrompt {
dir=$(getShortWorkingDirectory)
branch=$(getGitBranch)
status=$(getGitStatus)
time=$(date +%H:%M:%S)
before="───┤ "
after=" ├───"
# Change the line color if logged as root (sudo)
if [[ $(whoami) == "root" ]]; then
LineColor=$RootLineColor
fi
prompt="┌$before$time$after"
colored_prompt="$LineColor┌$before$TimeColor$time$LineColor$after"
if [[ $status != "nogit" ]]; then
# We are in a git repository
prompt="$prompt$before"
colored_prompt="$colored_prompt$before"
if [[ $status == "ok" ]]; then
# The current branch is clean
prompt="$prompt ✓ $branch"
colored_prompt="$colored_prompt $GitOkColor✓ $branch"
else
# The current branch is dirty
prompt="$prompt ✕ $branch"
colored_prompt="$colored_prompt $GitNotOkColor✕ $branch"
fi
prompt="$prompt$after"
colored_prompt="$colored_prompt$LineColor$after"
fi
prompt="$prompt$before$dir$after"
colored_prompt="$colored_prompt$before$WorkingDirColor$dir$LineColor$after"
# Counting the length of the generated prompt
length=$(echo $prompt | wc -m)
# Compute the length difference between total columns, and prompt length
let fill_count=$COLUMNS-$length
# Right pad the prompt to fill the screen width
while [[ $fill_count -gt 0 ]]; do
prompt="$prompt─"
colored_prompt="$colored_prompt─"
let fill_count=$fill_count-1
done
# Insert a new line before the prompt, for more clarity
echo ""
echo -e $colored_prompt
echo -ne "└──▶ "
}
# Replace the current prompt
export PS1="\$(gitPrompt)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment