Skip to content

Instantly share code, notes, and snippets.

@kg6zjl
Last active May 24, 2024 18:21
Show Gist options
  • Select an option

  • Save kg6zjl/94168e61a454971e51f6801156eb9dc0 to your computer and use it in GitHub Desktop.

Select an option

Save kg6zjl/94168e61a454971e51f6801156eb9dc0 to your computer and use it in GitHub Desktop.
All of my favorite git related aliases and functions
function git_master_branch() {
if [[ $(git branch -a | grep 'origin/main') = *origin/main* ]]; then
master_branch="main"
else
master_branch="master"
fi
}
function git_branch() {
branch="$(git branch 2> /dev/null | sed -e '/^[^*]/d' | tr -d '* ')"
echo ${branch}
}
function gp() { # git push the current branch and set upstream tracking
unset branch
git_master_branch
branch=$(git_branch)
if [[ "$branch" != *"$master_branch"* ]]; then
git push -u origin $branch
elif [[ "$branch" == *"$master_branch"* ]]; then
echo "refusing to push to master/main branch. create a branch and try again."
fi
}
function gm() { # git checkout master and git pull
git_master_branch # trigger the function to try and determine if master or main
git checkout $master_branch
checkoutrc=$?
branch=$(git_branch)
if [[ $(echo "$branch" | grep -v 'master\|main') || $checkoutrc != 0 ]]; then
echo "Failed to checkout ${master_branch}"
else
git pull
if [[ $? != 0 ]]; then
echo "Failed to pull ${master_branch}"
fi
fi
}
function gb() { # git checkout master, git pull, git checkout -b branch_name
gm #call gm function that git checkout master, git pull
if [[ ! -z "$1" ]]; then
git checkout -b $1
else
echo "You must pass a branch name"
fi
}
function pr() { #get url of repo to start pr process in a browser (this only seems to work with gitlab, needs work)
branch=$(git_branch)
echo "https://$(git ls-remote --get-url | sed 's|ssh:\/\/||g' | sed 's/git@//g' | sed 's/.git//g' | tr ':' '/')/merge_requests/new?merge_request[source_branch]=$branch"
}
alias gs="git status"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment