How Do I Switch Branch in Git?

How Do I Switch Branch in Git?

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
2

2 Answers

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>

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.