Skip to content

Instantly share code, notes, and snippets.

@HipsterBrown
Last active April 30, 2019 17:55
Show Gist options
  • Save HipsterBrown/7807aa472aefc1c94351a46dbbc0a5ac to your computer and use it in GitHub Desktop.
Save HipsterBrown/7807aa472aefc1c94351a46dbbc0a5ac to your computer and use it in GitHub Desktop.
Some handy bash functions for working in a git repo
# usage: load your local environment with a .env file or point to another file
# dotenv // load .env by default
# dotenv .env.staging // load the environment variables in .env.staging
dotenv() {
export $(cat ${1:-.env} | xargs);
}
# dynamically generate branch completion list
_list_branch_completions() {
COMPREPLY=($(compgen -W "$(git branch --list --sort=refname | tr -d '*')" "${COMP_WORDS[1]}"))
}
# usage: select a branch to change to, sorted alpha-numeric
change_branch() {
if [[ $# -ge 1 ]]; then
git checkout $branch
else
PS3="What branch would you like to select? (0 to exit)"$'\n'""
select branch in $(git branch --list --sort=refname | tr -d '*')
do
if [ -z $branch ]; then
return
else
git checkout $branch
return
fi
done
fi
}
complete -F _list_branch_completions change_branch
export -f change_branch
# usage: interactive select for cleaning up old branches
delete_branch() {
if [[ $# -ge 1 ]]; then
git branch -D $branch
else
PS3="What branch would you like to delete? (0 to exit)"$'\n'""
select branch in $(git branch --list --sort=refname | tr -d '*')
do
if [ -z $branch ]; then
return
else
git branch -D $branch
fi
done
fi
}
complete -F _list_branch_completions delete_branch
export -f delete_branch
# usage: get the latest version of a branch from remote
# refresh_branch // will change to a temp branch, delete previous branch, pull latest from origin
# refresh_branch branch_name // will delete branch_name, pull latest branch_name from origin
# refresh_branch branch_name remote_name // will delete branch_name, pull latest branch_name from remote_name
refresh_branch() {
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
BRANCH=(${1:-$CURRENT_BRANCH})
TEMP="temp-$BRANCH"
BRANCH_LIST=$(git branch | tr -d "*" | xargs)
if [[ $CURRENT_BRANCH == $BRANCH ]]; then
if [[ ! $BRANCH_LIST =~ $TEMP ]]; then
git branch $TEMP
fi
git checkout $TEMP
fi
git branch -D $BRANCH
git fetch ${2:-origin} $BRANCH:$BRANCH
if [[ $CURRENT_BRANCH == $BRANCH ]]; then
git checkout $BRANCH
fi
}
complete -F _list_branch_completions refresh_branch
export -f refresh_branch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment