How do I switch a branch in Git?
Asked Answered
C

2

5

I have executed the line below to switch to a new branch created by my teammate:

git checkout with-backend

I'm receiving the error below:

error: pathspec 'with-backend' did not match any file(s) known to git

I tried executing this command:

git branch -a

The with-backend branch created by my teammate is not listed. Below is the result listed:

* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/main
Casework answered 13/7, 2021 at 3:38 Comment(1)
Try issuing git fetch before executing these commands.Pustulant
I
3

Make sure you always pull latest changes from repo, before starting to work

git fetch <-- fetches all the latest changes from remote repo

OR

git pull <-- It is one step ahead of git fetch, it fetches remote changes and also merge local branch with remote branch

Induplicate answered 13/7, 2021 at 6:1 Comment(0)
P
7

First, switching branch is done with git switch (since Git 2.23, Q3 2019), not git checkout (which tries to manage both files and branches, making it confusing)

Second, git switch with-backend will work after git fetch because if its "guessing" mode:

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat as equivalent to

$ git switch -c <branch> --track <remote>/<branch>
Portie answered 13/7, 2021 at 6:40 Comment(2)
Git switch is labeled as "THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE."Churchgoer
@Churchgoer As I explained in 2020, the git switch command is "experimental" in name only, and is here to stay.Portie
I
3

Make sure you always pull latest changes from repo, before starting to work

git fetch <-- fetches all the latest changes from remote repo

OR

git pull <-- It is one step ahead of git fetch, it fetches remote changes and also merge local branch with remote branch

Induplicate answered 13/7, 2021 at 6:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.