I’m not sure why I’m unable to checkout a branch that I had worked on earlier. See the commands below (note: co
is an alias for checkout
):
ramon@ramon-desktop:~/source/unstilted$ git branch -a
* develop
feature/datts_right
feature/user_controlled_menu
feature/user_controlled_site_layouts
master
remotes/origin/HEAD -> origin/master
remotes/origin/develop
remotes/origin/feature/datts_right
remotes/origin/master
ramon@ramon-desktop:~/source/unstilted$ git co feature/user_controlled_site_layouts
error: pathspec 'feature/user_controlled_site_layouts' did not match any file(s) known to git.
I’m not sure what it means, and I can’t seem to find anything I can understand on Google.
How do I checkout that branch, and what may I have done to break this?
UPDATE:
I found this post, and running git show-ref
gives me:
97e2cb33914e763ff92bbe38531d3fd02408da46 refs/heads/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/heads/feature/datts_right
11a90dae8897ceed318700b9af3019f4b4dceb1e refs/heads/feature/user_controlled_menu
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/heads/master
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/HEAD
e7c17eb40610505eea4e6687e4572191216ad4c6 refs/remotes/origin/develop
c438c439c66da3f2356d2449505c073549b221c1 refs/remotes/origin/feature/datts_right
c889b37a5ee690986935c9c74b71999e2cf3c6d7 refs/remotes/origin/master
23768aa5425cbf29d10ff24274adad42d90d15cc refs/stash
e572cf91e95da03f04a5e51820f58a7306ce01de refs/tags/menu_shows_published_only
429ebaa895d9d41d835a34da72676caa75902e3d refs/tags/slow_dev
UPDATE on .git
directory (user_controlled_site_layouts
is in the refs/heads/feature folder
):
$ ls .git/refs/heads/feature/
datts_right user_controlled_menu user_controlled_site_layouts
$ cat .git/refs/heads/feature/user_controlled_site_layouts
3af84fcf1508c44013844dcd0998a14e61455034
UPDATE on git show 3af84fcf1508c44013844dcd0998a14e61455034
$ git show 3af84fcf1508c44013844dcd0998a14e61455034
commit 3af84fcf1508c44013844dcd0998a14e61455034
Author: Ramon Tayag <xxx@xxxxx.xxx>
Date: Thu May 12 19:00:03 2011 +0800
Removed site layouts migration
diff --git a/db/schema.rb b/db/schema.rb
index 1218fc8..2040b9f 100755
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20110511012647) do
+ActiveRecord::Schema.define(:version => 20110503040056) do
create_table "attachments", :force => true do |t|
t.string "name"
@@ -205,15 +205,6 @@ ActiveRecord::Schema.define(:version => 20110511012647) do
t.integer "old_id"
end
- create_table "site_layouts", :force => true do |t|
- t.string "name"
- t.text "description"
- t.text "content"
- t.integer "site_id"
- t.datetime "created_at"
- t.datetime "updated_at"
- end
-
create_table "site_styles", :force => true do |t|
t.text "published"
t.datetime "created_at"
Scenarios that emerge
In the local init, a repository is created, and then a develop ment branch is created, on which file operations are performed, followed by changes made by commit.
$ git init Initialized empty Git repository in D:/practice/testBranch/.git/ $ git checkout -b develop Switched to a new branch 'develop' $ vim a.txt $ git add a.txt $ git commit -m "add a new file" [develop (root-commit) f9ac3b8] add a new file 1 file changed, 1 insertion(+) create mode 100644 a.txt
Then you cut to the master branch and do the file operation. Then the following mistakes will occur:
$ git checkout master error: pathspec 'master' did not match any file(s) known to git.
Reasons for the problem
Command parsing
The git init command creates a master branch by default and points the HEAD (which is a special pointer to the current local branch) to that branch. Nevertheless, you can’t see any branches when you view local and remote branches through the GIT branch-a command.
The git checkout master command actually does two things: one is to make HEAD refer back to the master branch; the other is to restore the working directory to the snapshot content that the master branch refers to.
problem analysis
After HEAD refers back to the master branch, it is necessary to restore the working directory to the content that the master branch refers to. But since you’ve been working on the develop ment branch since the beginning, the working directory corresponding to the master branch is equivalent to nothing, so that no files can be matched.
How to solve
You just need to initialize a repository, first do some commit operations on the master branch, such as adding a README.md file, so that you really create a master branch. For example:
$ git init Reinitialized existing Git repository in D:/practice/testBranch/.git/ $ vim README.md $ git add README.md warning: LF will be replaced by CRLF in README.md. The file will have its original line endings in your working directory. $ git commit -m "add a new file" [master (root-commit) 0e8c7c3] add a new file 1 file changed, 1 insertion(+) create mode 100644 README.md $ git push Counting objects: 3, done. Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done. Total 3 (delta 0), reused 0 (delta 0) remote: remote: Create a pull request for 'master' on GitHub by visiting: remote: https://github.com/benben/testBranch/pull/new/master remote: To github.com:benben/testBranch.git * [new branch] master -> master
When push ing, you can see the prompt to create a master branch in the remote warehouse, and the local master branch points to the remote master branch.
Then you can see all local and remote branches through git branch-a. Then you can create other branches and switch between master branches at will.
$ git branch -a * master remotes/origin/master
When switching branches, be aware that the files in your working directory will be changed. If you switch to an older branch, your working directory will be restored to what it looked like when it was last submitted. If Git can’t do this cleanly, it will prohibit branch switching.
The scene that emerges
Init init a warehouse locally, then create a develop
branch, and do file operations on this branch, followed by the changes made by commit
.
$ git init
Initialized empty Git repository in D:/practice/testBranch/.git/
$ git checkout -b develop
Switched to a new branch 'develop'
$ vim a.txt
$ git add a.txt
$ git commit -m "add a new file"
[develop (root-commit) f9ac3b8] add a new file
1 file changed, 1 insertion(+)
create mode 100644 a.txt
And then you go to the master
branch, and you do the file manipulation. This is where the following error occurs:
$ git checkout master
error: pathspec 'master' did not match any file(s) known to git.
The cause of the problem
The command parsing
By default, the git init
command creates a master
branch and points the HEAD
(which is a special pointer to the current local branch) to that branch. However, when you view local and remote branches using the git branch-a
command, you won’t see any branches.
git checkout master
command actually does two things: one is to make HEAD
point back to master
branch; The other is to restore the working directory to the snapshot content pointed to by the master
branch.
Problem analysis
After the HEAD
refers back to the master
branch, the working directory needs to be restored to the content pointed to by the master
branch. But since you’ve been working on the develop
branch since the beginning, the working directory corresponding to the master
branch is as good as nothing, so you can’t match any files.
How to solve
You just need to initialize a warehouse and first do some commit
on the master
branch, such as adding a readme.md
file, thus creating a master
branch. Such as:
$ git init
Reinitialized existing Git repository in D:/practice/testBranch/.git/
$ vim README.md
$ git add README.md
warning: LF will be replaced by CRLF in README.md.
The file will have its original line endings in your working directory.
$ git commit -m "add a new file"
[master (root-commit) 0e8c7c3] add a new file
1 file changed, 1 insertion(+)
create mode 100644 README.md
$ git push
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'master' on GitHub by visiting:
remote: https://github.com/benben/testBranch/pull/new/master
remote:
To github.com:benben/testBranch.git
* [new branch] master -> master
When you do a push
operation, you will see that a master
branch has been created in the remote warehouse, and the local master
branch points to the remote master
branch.
then you can see all local and remote branches by using git branch -a
. You can then create additional branches and switch between master branches at will.
$ git branch -a
* master
remotes/origin/master
When switching branches, make sure that the files in your working directory are changed. If you switch to an older branch, your working directory will revert to the way it looked the last time the branch was committed. If Git cannot do this cleanly, it will forbid switching branches.
Read More:
Maria Yudina
Posted on Nov 14, 2021
• Updated on Dec 3, 2022
Sometimes after repository checkout you can encounter the error trying to switch branches:
git checkout branch_name
error: pathspec 'branch_name' did not match any file(s) known to git
Enter fullscreen mode
Exit fullscreen mode
To fix that you can remove remote origin and link it again.
First, check the remote origin:
git remote -v
origin git@github.com:company/project_name (fetch)
origin git@github.com:company/project_name (push)
Enter fullscreen mode
Exit fullscreen mode
Then remove origin:
git remote remove origin
Enter fullscreen mode
Exit fullscreen mode
And add remote origin again with correct path from your repository (copy from GitHub/GitLab/etc.):
git remote add origin git@github.com:company/project_name.git
Enter fullscreen mode
Exit fullscreen mode
After that run:
git pull --ff-only
Enter fullscreen mode
Exit fullscreen mode
And set upstream to origin branch:
git branch --set-upstream-to=origin/current_branch
Enter fullscreen mode
Exit fullscreen mode
After this you should be able to switch between the branches as usual.
This error message indicates that Git was unable to checkout the specified branch because it does not exist. This can happen for a few different reasons, including the following:
- The branch name is misspelled or mistyped.
- The branch has already been deleted or is no longer available.
- The branch exists in a remote repository, but it has not yet been pulled or fetched to the local repository.
To fix this error, you will need to verify that the branch name is correct and that the branch exists in the local repository. If the branch name is correct and the branch still does not exist, you may need to pull or fetch the branch from the remote repository where it exists.
If the branch has already been deleted or is no longer available, you will need to create a new branch with a different name or switch to a different existing branch.
Overall, this error can be resolved by checking the branch name and ensuring that the branch exists in the local repository. If necessary, you can also try pulling or fetching the branch from the remote repository where it exists.
Появилась сцена
в местном масштабеinit
Склад, а затем создатьdevelop
Ветка, и выполните файловые операции в этой ветви, затемcommit
Модификации сделаны.
$ git init
Initialized empty Git repository in D:/practice/testBranch/.git/
$ git checkout -b develop
Switched to a new branch 'develop'
$ vim a.txt
$ git add a.txt
$ git commit -m "add a new file"
[develop (root-commit) f9ac3b8] add a new file
1 file changed, 1 insertion(+)
create mode 100644 a.txt
Затем вы сокращаете доmaster
Выполните файловые операции на ветке. В это время появится следующая ошибка:
$ git checkout master
error: pathspec 'master' did not match any file(s) known to git.
Причина проблемы
Разбор команд
git init
Команда создаст один по умолчаниюmaster
Филиал и воляHEAD
(Это специальный указатель, который указывает на локальную ветвь, где он находится в данный момент) указывает на эту ветвь. Несмотря на это, вы проходитеgit branch -a
Команды для просмотра локальной и удаленной веток вы не увидите ни одной ветки.
git checkout master
Команда на самом деле делает две вещи: одна должна сделатьHEAD
Указывая назадmaster
Филиал; второе — восстановить рабочий каталог вmaster
Содержимое снимка, на которое указывает ветка.
Анализ проблем
вHEAD
Указывая назадmaster
После ветвления необходимо восстановить рабочий каталог вmaster
Содержание, на которое указывает ветка. Но так как вы были с самого началаdevelop
Работаем на ветке,master
Рабочий каталог, соответствующий ветви, ничем не эквивалентен, так что ни один файл не совпадает.
Как исправить
Вам нужно только сначалаmaster
Сделать некоторые на веткеcommit
Операции, такие как добавление одногоREADME.md
Файл, так что настоящийmaster
Отделение. Например:
$ git init
Reinitialized existing Git repository in D:/practice/testBranch/.git/
$ vim README.md
$ git add README.md
warning: LF will be replaced by CRLF in README.md.
The file will have its original line endings in your working directory.
$ git commit -m "add a new file"
[master (root-commit) 0e8c7c3] add a new file
1 file changed, 1 insertion(+)
create mode 100644 README.md
$ git push
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'master' on GitHub by visiting:
remote: https://github.com/benben/testBranch/pull/new/master
remote:
To github.com:benben/testBranch.git
* [new branch] master -> master
В процессеpush
Во время работы вы можете увидеть подсказку и создатьmaster
Филиал и местныйmaster
Филиал к удаленномуmaster
Отделение.
В этот раз вы проходитеgit branch -a
Вы можете увидеть все локальные и удаленные филиалы. Затем вы можете создавать другие ветви и произвольно переключаться между основными ветвями.
$ git branch -a
* master
remotes/origin/master
При переключении веток обязательно обратите внимание, что файлы в вашем рабочем каталоге будут изменены. Если вы переключитесь на более старую ветку, ваш рабочий каталог будет восстановлен до того, который был, когда ветка была зафиксирована в последний раз. Если Git не может выполнить эту задачу чисто, он запретит переключение веток.