Skip to content

Instantly share code, notes, and snippets.

@SynCap
Last active September 27, 2023 11:53
Show Gist options
  • Save SynCap/30b513e40ada3e171e99e57d25c45f1c to your computer and use it in GitHub Desktop.
Save SynCap/30b513e40ada3e171e99e57d25c45f1c to your computer and use it in GitHub Desktop.
Rename Git branch locally and remote with PowerShell
# Raname current branch Locally and Remote
function Rename-GitBranch {
[CmdletBinding()]
param(
[Parameter(mandatory=$true)][String] $OldName,
[Parameter(mandatory=$true)][String] $NewName,
[String] $UpstreamName = 'origin'
)
# Rename the local branch to the new name
git branch -m $OldName $NewName
# Delete the old branch on remote - where $remote is, for example, origin
# `git push $remote --delete $OldName`
# OR shorter way to delete remote branch [:]
git push $UpstreamName :$OldName
# Prevent git from using the old name when pushing in the next step.
# Otherwise, git will use the $OldName on upstream instead of $NewName.
git branch --unset-upstream $OldName
# Push the new branch to remote
git push $UpstreamName $NewName
# Reset the upstream branch for the NewName local branch
git push $UpstreamName -u $NewName
# Somtimes when delete of branch is prohibited at remote server
# (default branch at GitHub for example)
# then `delete remote` operation fails and old refs stays locally
# even you kill manually old branch at remote server
# so old refs have to be cleaned at local repo configs
$oldRef = Join-Path (git rev-parse --git-dir) "refs\remotes\$UpstreamName\$OldName"
if (Test-Path $oldRf) {
Remove-Item $oldRef
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment