Skip to content

Instantly share code, notes, and snippets.

@jseed
Last active June 23, 2020 20:25
Show Gist options
  • Save jseed/db75185da2132c41cd3885b5666d8dfe to your computer and use it in GitHub Desktop.
Save jseed/db75185da2132c41cd3885b5666d8dfe to your computer and use it in GitHub Desktop.
Defining custom sub commands, git example
#!/bin/bash
## Custom git commands
unset -f git > /dev/null 2>&1 # Remove custom function if already set (i.e. if `reload` is called)
GIT=$(which git) # Get path to original git executable
git() {
ERROR=1
# Fail if not in a repository
eval $GIT status > /dev/null
if [ $? -ne 0 ]; then
return $ERROR
fi
# Checkout a branch, applying the current changes
if [ "$1" = "switch" ]; then
if [ -z "$2" ]; then
echo "Missing argument(s)" >&2
echo "Usage: git switch <BRANCH_NAME>" >&2
return $ERROR
fi
EXISTS=`eval $GIT rev-parse --quiet --verify $2`
if [ -z "$EXISTS" ]; then
echo "No branch named '$2'" >&2
return $ERROR
fi
git stash
git checkout "$2"
git stash apply
# Hard reset to the origin of the current branch
elif [ "$1" = "reset-origin" ]; then
CURRENT_BRANCH=`eval $GIT rev-parse --abbrev-ref HEAD`
eval $GIT reset --hard origin/$CURRENT_BRANCH
# If no matching custom command, execute against git
else
eval $GIT "$@"
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment