Git push detached HEAD, and set upstream to remote branch

今天遇到的狀況是,不小心把 local branch detach, 而且原本的 local branch 整個被改爛,然後要把修改過的東西(detached HEAD) push 回 remote branch,並把爛掉的 local branch track 上正確的 remote branch

#先把正確的 HEAD push 回目的branch
$ git push origin HEAD:mytestbranch
Counting objects: 3, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 302 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To git@git.test.com:gittest.git
   8dbf84e..1c4e704  HEAD -> mytestbranch
#把被搞爛的 local branch 先移除
$ git branch -d mytestbranch
Deleted branch mytestbranch (was f8ae14e)
#如果這個被搞爛的 branch 有其他尚未 commit 的資料,會出現 error message,改用-D刪除
#例如 $ git branch -D mytestbranch
#重新建立 local branch ,然後 track remote branch
$ git checkout -b mytestbranch
Switched to a new branch 'mytestbranch'
$ git branch -u origin/mytestbranch
Branch mytestbranch set up to track remote branch mytestbranch from origin.