You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Git是否有单命令切换至分支最新远程版本的快捷方式?

Great question! As a fellow code reviewer dealing with force-pushed branches regularly, I totally get the hassle of those multi-step commands just to get the latest version of a feature branch. Luckily, Git has a few one-line solutions that can simplify your workflow:

1. Use git checkout -B to reset and switch in one go

The -B flag lets you either create a new branch or reset an existing local branch to match the remote version, then switch to it immediately. It’s perfect for handling force-pushed scenarios:

git checkout -B feature origin/feature
  • If feature already exists locally, this will reset it to the exact state of origin/feature (overwriting any local changes, so make sure you don’t have uncommitted work you need to keep!).
  • If it doesn’t exist, it creates a new local feature branch tracking origin/feature.

2. For Git 2.23+, use git switch -C (modern alternative)

Git 2.23 introduced git switch as a more intuitive replacement for branch-related git checkout operations. The -C flag works exactly like -B here:

git switch -C feature origin/feature

This does the same thing as the command above, but feels more explicit for switching branches.

3. Fetch and update the branch in one line (explicit fetch first)

If you want to explicitly fetch remote updates before syncing the local branch, you can chain commands:

git fetch origin feature:feature && git checkout feature
  • git fetch origin feature:feature updates your local feature branch to match origin/feature directly (even if there was a force push).
  • The && ensures it only switches to the branch if the fetch/update succeeds.

Bonus: Create a Git alias for even easier use

If you do this often, setting up an alias will save you typing every time. Add this to your global .gitconfig file:

[alias]
  fresh-checkout = !git fetch --all --prune && git checkout -B "$1" "origin/$1"

Now you can just run:

git fresh-checkout feature

This combines fetching all remote updates (with pruning stale branches) and resetting/checking out the target branch in one simple command.

Just a quick heads-up: All these commands will overwrite local changes to the branch, so make sure you stash or commit any work you want to keep before running them!

内容的提问来源于stack exchange,提问作者Trident D'Gao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:50:24