TL;DR
Using git switch rather than git checkout. More details are on this page.
I think the answer is obsolete. Git split some functions of checkout to switch and restore now.
The following is my summary:
If you want to update something for a remote branch, you should create a local branch to "track" the remote branch. You can update anything you want in local and finally push to remote. If you check out to the remote branch directly after cloning your repository, you may see the "detached HEAD" status and the following message from Git:
Note: switching to 'origin/asd'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:
git switch -c <new-branch-name>
Or undo this operation with:
git switch -
Turn off this advice by setting config variable advice.detachedHead to false
HEAD is now at d3e1083 Update a
So how can we create a local branch to track a remote branch?
To create a local branch to track a remote branch, you can use git checkout <remote branch name> or git switch <remote branch name>. If you have a file or folder has same name as your remote branch name, git checkout would output some error message, but git switch can work normally!
Example:
See all branches, and we want to create a local branch to track the remote branch remotes/origin/asd, and we also have the file name asd:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/asd
remotes/origin/ereres
remotes/origin/master
remotes/origin/zxc
$ ls
a asd
The filename is same as remote branch, and Git should output some error messages if we are using the git checkout command to create a local branch to track a remote branch
$ git checkout asd
fatal: 'asd' could be both a local file and a tracking branch.
Please use -- (and optionally --no-guess) to disambiguate
It works if we are using git switch!
$ git switch ereres
Branch 'ereres' set up to track remote branch 'ereres' from 'origin'.
Switched to a new branch 'ereres'
$ git branch -vv
* ereres 3895036 [origin/ereres] Update a
master f9e24a9 [origin/master] Merge branch 'master' of