Skip to content

Instantly share code, notes, and snippets.

@Lewiscowles1986
Forked from lttlrck/gist:9628955
Last active June 13, 2020 08:53
Show Gist options
  • Save Lewiscowles1986/bc23b055d30fffd71f6c4c974089f1c4 to your computer and use it in GitHub Desktop.
Save Lewiscowles1986/bc23b055d30fffd71f6c4c974089f1c4 to your computer and use it in GitHub Desktop.
rename git branch locally and remotely

Git Rename Script

This is a fork of https://gist.github.com/lttlrck/9628955 to make the renaming of branches simpler.

Usage

  1. Ensure the script is executable.
  2. git-rename.sh [oldbranchname] newbranchname [upstreamname]

conventions

  • [anything] - denotes an optional positional argument
  • git-rename.sh - is the name of this script

Troubleshooting

Using on the current active branch name

If your target new name is your current branch name. This won't work

Pushing to a branch that exists remotely

This does not force push. If you have a remote branch, this should not be able to push, even if your local is out of sync. Please avoid modifying to force push. That can be dangerous.

The script does not work

It specifies a shell, which I'm not ecstatic about, but seemed necesarry for the shellcheck to stop erroring. I guess it removes ambiguity. If this becomes a problem, please feel free to change to bourne again or zsh. Other shell interpreters are expected not to work.

If you have bash or zsh installed, you can call the script using bash git-rename.sh [args] or zsh git-rename.sh [args]

#!/bin/sh
TARGET="$(git rev-parse --abbrev-ref HEAD)"
NEWNAME="unknown"
UPSTREAM="origin"
must_be_new_branch() {
>&2 echo "This script requires a new branch name"
echo "Usage: $0 [oldbranchname] newbranchname [upstreamname]"
exit 1
}
if [ $# -lt 1 ]; then
must_be_new_branch
fi
if [ $# -ge 2 ]; then
TARGET="$1"
NEWNAME="$2"
else
NEWNAME="$1"
fi
if [ "$TARGET" == "$NEWNAME" ]; then
must_be_new_branch
fi
if [ $# -ge 3 ]; then
UPSTREAM="$3"
fi
git checkout -b "$NEWNAME" # Fork branch locally
git push --set-upstream "$UPSTREAM" "$NEWNAME" > /dev/null 2>&1 || \
(echo "failed to create remote" && git checkout "$TARGET" && exit 2) # Push the new branch, set local branch to track remote
git push "$UPSTREAM" --delete "$TARGET" > /dev/null 2>&1 || \
echo "failed to delete remote" # Delete the remote old branch
git branch -D "$TARGET" # Force delete the old branch locally
@Lewiscowles1986
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment