Skip to content

Instantly share code, notes, and snippets.

@ben-cohen
Last active July 29, 2021 16:47
Show Gist options
  • Save ben-cohen/e2f96d5dc7e632ef86e0be9c132bfd1f to your computer and use it in GitHub Desktop.
Save ben-cohen/e2f96d5dc7e632ef86e0be9c132bfd1f to your computer and use it in GitHub Desktop.
Check whether git is in a special state
#!/bin/bash
#
# git_check_status.sh: check whether git is in a special state
#
# Ben Cohen, July 2021
#
# This script returns failure if the current directory is a git worktree
# that is in a special state - merge, rebase, bisect or detached HEAD - or
# returns success if the worktree is in a normal state, or the current
# directory is not a git worktree.
#
# If invoked with the option "-v" then a description will be printed if
# git is in a special state.
#
# The following can be used to provide a warning in your bash prompt,
# instead of discovering that you have been working with a detached HEAD
# for the last three days...
#
# PS1="\[\033[7;36m\]\$(git_check_status.sh -v)\[\033[00m\]$PS1"
#
usage() {
echo "Usage: $0 [-v]" 1>&2
exit 1
}
while getopts "v" o; do
case "${o}" in
v) verbose=1
;;
*) usage
;;
esac
done
if ! git rev-parse --is-inside-work-tree >& /dev/null
then
# The current directory is not inside a git repo
exit 0
fi
GITDIR=$(git rev-parse --git-dir)
if [ -e "$GITDIR/MERGE_HEAD" ]
then
# Doing a merge
[ -n "$verbose" ] && echo -n "MERGING"
exit 2
fi
if [ -e "$GITDIR/BISECT_START" ]
then
# Doing git bisect
[ -n "$verbose" ] && echo -n "BISECTING"
exit 3
fi
if [ -e "$GITDIR/rebase-merge" -o -e "$GITDIR/rebase-apply" ]
then
# Doing git rebase
[ -n "$verbose" ] && echo -n "REBASING"
exit 4
fi
if [ "$(git rev-parse --abbrev-ref --symbolic-full-name HEAD)" = "HEAD" ]
then
# HEAD is detached
[ -n "$verbose" ] && echo -n "OFF-BRANCH"
exit 1
fi
# The current directory is in a git repo but not in a special state
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment