简体   繁体   中英

git reset all branches to origin?

I want to reset multiple branches to their origin version. So,

git fetch --all
for b in master work; do
  git switch $b; git reset --hard origin/$b
done

But simpler? I've thought about deleting all branches so they get recreated, but one has to be checked out and will error out.

Edit : the scenario is that origin often rewrites multiple branches with impunity. The answer below also gave me the idea of saving various states to backup refs -- which is a nice bonus.

You don't need to switch to the branches. You can simply re-create a branch and have it point to any arbitrary ref:

 git branch -f branchname "$target"

(As an added bonus, unstaged changes in your working tree won't be affected, as compared to git reset --hard which will wipe any local changes.)

When being used in scripts git branch should be avoided and it is better to use for-each-ref :

 git for-each-ref 'refs/remotes/origin' --format='%(refname:strip=3)' \ | while read ref; do git branch -f "$ref" "origin/$ref"; done

If you are only interested in creating a "backup" of the current state of the remote tracking branches, git push or git fetch can help by using the current clone as remote.

Either command will replicate all branches of the origin remote into a new (local) branch hierarchy with prefix backup/ , ie origin/dev becomes backup/dev :

 git fetch. 'refs/remotes/origin/*:refs/heads/backup/*' # or: git push. 'refs/remotes/origin/*:refs/heads/backup/*'

Or to fetch directly from the remote into a separate set of local refs:

 git fetch origin 'refs/heads/*:refs/heads/backup/*'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM