Did not match any file s known to git ошибка

I am trying to upload a Ruby app to Heroku. I start with git init and then I type git add . and then I use git commit -m initial commit. Whenever I use git commit -m, I receive an error message s...

I am trying to upload a Ruby app to Heroku. I start with git init and then I type git add . and then I use git commit -m initial commit.

Whenever I use git commit -m, I receive an error message saying:

git commit error:pathspect ‘commit’ did not match any file(s) known to git.

I have been told that this is happening because the arguments are in the wrong order.

The thing I noticed is that when I use git add . it will not list the files that are being added because it will just go to the next line.

I suspect that I am having this problem because my files are not really being added.

I would appreciate any advice about how to correct this problem.

Kenny Evitt's user avatar

Kenny Evitt

9,0635 gold badges66 silver badges90 bronze badges

asked Jun 5, 2013 at 22:55

user2457644's user avatar

The command line arguments are separated by space. If you want provide an argument with a space in it, you should quote it. So use git commit -m "initial commit".

answered Jun 5, 2013 at 22:58

kan's user avatar

kankan

28k7 gold badges71 silver badges101 bronze badges

4

I would just like to add—

In windows the commit message should be in double quotes (git commit -m "initial commit" instead of git commit -m 'initial commit'), as I spent about an hour, just to figure out that single quote is not working in windows.

toto_tico's user avatar

toto_tico

17.2k8 gold badges94 silver badges111 bronze badges

answered Sep 8, 2014 at 0:32

Nicks's user avatar

NicksNicks

15.9k8 gold badges57 silver badges65 bronze badges

6

In my case, this error was due to special characters what I was considering double quotes as I copied the command from a web page.

answered Nov 9, 2014 at 16:11

zeeawan's user avatar

zeeawanzeeawan

6,5672 gold badges50 silver badges54 bronze badges

I figured out mistake here use double quotations instead of single quotations.

change this

git commit -m 'initial commit'

to

git commit -m "initial commit"

agarcian's user avatar

agarcian

3,8893 gold badges30 silver badges54 bronze badges

answered Sep 22, 2018 at 4:33

saigopi.me's user avatar

saigopi.mesaigopi.me

13k2 gold badges79 silver badges54 bronze badges

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

answered Sep 11, 2016 at 13:11

Linux_Google's user avatar

Had this happen to me when committing from Xcode 6, after I had added a directory of files and subdirectories to the project folder. The problem was that, in the Commit sheet, in the left sidebar, I had checkmarked not only the root directory that I had added, but all of its descendants too. To solve the problem, I checkmarked only the root directory. This also committed all of the descendants, as desired, with no error.

answered Feb 5, 2015 at 0:04

Jerry Krinock's user avatar

I have encounter the same problem. my syntax has no problem.
What I found is that I copied and pasted git commit -m «comments» from my note. I retype it, the command execute without issue. It turns out the and » « are the problem when I copy paste to terminal.

answered Jul 3, 2019 at 13:26

Haibin Chen's user avatar

1

In my case, the problem was I used wrong alias for git commit -m. I used gcalias which dit not meant git commit -m

answered Dec 4, 2019 at 11:09

T G's user avatar

Type the command git commit -m "Initial Commit" yourself in the terminal/command prompt instead of copy and paste from web page. I believe this will help.

answered Jun 25, 2022 at 11:59

Freeman's user avatar

if there are anybodys using python os to invoke git,u can use os.system(‘git commit -m » ‘+str(comment)+'»‘)

answered Sep 12, 2017 at 2:29

未来陆家嘴顶尖的投资人's user avatar

未来陆家嘴顶尖的投资人未来陆家嘴顶尖的投资人

1,71820 silver badges19 bronze badges

In my case the problem was I had forgotten to add the switch -m before the quoted comment. It may be a common error too, and the error message received is exactly the same

answered Aug 30, 2019 at 19:01

Javier D.'s user avatar

Javier D.Javier D.

751 silver badge10 bronze badges

Solved! Here is how I solved this issue:

  1. Made an app on Heroku first and prepared all the codes in local_folder to push into it.
  2. Cloned the remote app using heroku git:clone -a app_name
  3. then cd app_name
  4. then copied all the codes into this folder from local_folder
  5. then git add .
  6. then git commit -am "initial commit"
  7. then git push heroku master
  8. Viola!

answered Jul 17, 2021 at 17:07

Deepak Mittal's user avatar

Had the same problem. " or ' doesn’t work for me.

In my case, i used git commit to add commit-msg. After this commit, git commit -m 'xxx' works as before.

answered Jan 31 at 13:11

SIMIN's user avatar

SIMINSIMIN

11 bronze badge

Maria Yudina

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.

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.

Задача описана тут Как использовать git checkout?
Osmocom — система, позволяющая перепрошивать телефоны на DSP процессоре Calypso.
Я попробовал сделать так https://pastebin.com/qYE1yuxZ
Но с помощью этой инструкции я успешно прошиваю только RAM, это не то то мне нужно, чтобы прошить флеш память нужен файл menu.e88loader.bin, говорят, что он есть в ветке jolly/menu этого проекта, но я не могу его получить.
На шаге 3.3 инструкции с Pastebin я клонирую мастер ветку, затем вхожу в неё и выполняю git checkout jolly/menu. Успешно. Но затем, при попытке make я получаю ошибки типа

Makefile:488: ошибка выполнения рецепта для цели «timer.lo»
make[4]: *** [timer.lo] Ошибка 1
make[4]: выход из каталога «/root/osmocombb/master/src/shared/libosmocore/build-target/src»
Makefile:366: ошибка выполнения рецепта для цели «all»
make[3]: *** [all] Ошибка 2
make[3]: выход из каталога «/root/osmocombb/master/src/shared/libosmocore/build-target/src»
Makefile:507: ошибка выполнения рецепта для цели «all-recursive»
make[2]: *** [all-recursive] Ошибка 1
make[2]: выход из каталога «/root/osmocombb/master/src/shared/libosmocore/build-target»
Makefile:379: ошибка выполнения рецепта для цели «all»
make[1]: *** [all] Ошибка 2
make[1]: выход из каталога «/root/osmocombb/master/src/shared/libosmocore/build-target»
Makefile:34: ошибка выполнения рецепта для цели «shared/libosmocore/build-target/src/.libs/libosmocore.a»
make: *** [shared/libosmocore/build-target/src/.libs/libosmocore.a] Ошибка 2

In case, you are trying to git checkout a tag and you get the following error:

error: pathspec 'tags/<tag-name>' did not match any file(s) known to git

It is likely that you either misspelled the tag name or your local is not in sync with your remote repository. To find and fix the error you can simply do the following:

  • Make sure the tag name is correct;
  • Make sure the tag name exists locally.

Make Sure the Tag Name Is Correct

The git tag that you’re trying to checkout might have been misspelled. You can check the spelling against a list of all available tags. For example, one way you can do so is by using the following command:

git tag

Make Sure the Tag Name Exists

The git tag that you’re trying to checkout might not exist. It could be that your local tags are not in sync with the remote ones. You can fetch all tags from the corresponding remote, for example, by using the following command:

git fetch --all --tags --prune

Hope you found this post useful. It was published 26 Dec, 2021. Please show your love and support by sharing this post.

Я не уверен, почему я не смог проверить ветку, с которой я работал раньше. См. Приведенные ниже команды (примечание: co является псевдонимом для checkout):

[email protected]:~/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
[email protected]:~/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.

Я не уверен, что это значит, и я не могу найти ничего, что я могу понять в Google.

Как проверить эту ветку и что я могу сделать, чтобы сломать это?

UPDATE

Я нашел этот пост, и запуск git show-ref дает мне:

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 в каталоге .git (user_controlled_site_layouts находится в 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

ОБНОВЛЕНИЕ на git show 3af84fcf1508c44013844dcd0998a14e61455034

$ git show 3af84fcf1508c44013844dcd0998a14e61455034
commit 3af84fcf1508c44013844dcd0998a14e61455034
Author: Ramon Tayag <[email protected]>
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 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"

13 май 2011, в 08:44

Поделиться

Источник

40 ответов

Попробуйте git fetch, чтобы ваш локальный репозиторий получал всю новую информацию от github. Он просто берет информацию о новых ветких и фактическом коде. После этого git checkout должен работать нормально.

MarkoHiel
07 сен. 2011, в 14:24

Поделиться

Я получал эту ошибку, когда пытался оформить заказ на новую ветку:

ошибка: pathspec ‘BRANCH-NAME’ не соответствует ни одному из файлов, известных git.

Когда я попробовал git checkout origin/<BRANCH-NAME>, я получил отдельную ГОЛОВУ:

(отстранен от происхождения /)

Наконец, я сделал следующее, чтобы решить проблему:

git remote update
git fetch 
git checkout --track origin/<BRANCH-NAME>

Mayank
15 сен. 2015, в 06:42

Поделиться

Я получил эту ошибку для ветки, которая была удаленной и не имела локальной ветки отслеживания. Хотя я уверен, что проверил удаленные ветки через простой

git checkout feature/foo

в прошлом, чтобы обойти эту ошибку, я должен был

git checkout -t -b feature/foo origin/feature/foo

Я не знаю, что я сделал, чтобы попасть в эту ситуацию.

Gregory McIntyre
31 май 2011, в 01:07

Поделиться

Если вы удалили ветку с помощью git branch -D yourbranchname и снова вытащили/клонировали свое репо, вам может понадобиться снова создать локальную ветку.

Попробуйте:

git checkout -b yourbranchname

Francisco Alvarez
04 фев. 2014, в 00:14

Поделиться

Git Пользователи Windows остерегаются — без параметров --icase-pathspecs или GIT_ICASE_PATHSPECS = 1 env var, что git pathspecs будут чувствительны к регистру, в которых case

git checkout origin/FooBranch "Some/Path/To/File.txt"

не совпадает с

git checkout origin/FooBranch "Some/Path/To/File.txt"

StuartLC
21 фев. 2014, в 09:36

Поделиться

У меня есть те же вопросы, и я получил некоторую информацию по этой ссылке: git fetch не извлекает все ветки

Итак, теперь я не уверен, как эта ситуация произошла, по крайней мере, мы можем ее решить:

Шаг 1. Проверьте настройку «remote.origin.fetch», должно быть как

$git config —get remote.origin.fetch

+ ссылки/головки/private_dev_branch: ссылки/пультов ДУ/происхождение/private_dev_branch

Шаг 2. Измените «remote.origin.fetch», чтобы получить все

$git config remote.origin.fetch «+ refs/heads/*: refs/remotes/origin/*»

$git config —get remote.origin.fetch

+ ссылки/главы/*: ссылки/пультов ДУ/происхождение/*

Затем вы можете попробовать «git pull» (возможно, «git fetch origin» также работает, но я не пробовал), чтобы получить всю ветвь.

bearzyj
08 авг. 2017, в 05:45

Поделиться

Если имя ветки отсутствует, и у вас нет никакого файла с ограниченным доступом, попробуйте это

git fetch && git checkout <branch name>

Sajin M Aboobakkar
18 май 2017, в 12:20

Поделиться

git pull

Это просто исправило это для меня :)

OpMt
29 авг. 2018, в 00:29

Поделиться

Я получил это, когда сделал следующее:

  • Используемая IntelliJ IDE, подключенная к git
  • Создан новый файл и добавлен в git
  • Переименован новый файл

Когда я попытался проверить каталог, я получил эту ошибку.

Чтобы исправить:

Я открыл репо в расширениях git. Я увидел, что файл (со старым именем) был поставлен. Но поскольку он больше не существует, он не может быть зафиксирован.

Я просто отключил этот файл.

Затем я снова добавил файл (на этот раз правильно названный) в git и зафиксировал без ошибок.

Somaiah Kumbera
26 нояб. 2014, в 16:16

Поделиться

У меня была эта проблема сегодня, я пытался git checkout foo и получил error: pathspec 'foo' did not match any file(s) known to git.

Оказывается, я ошибался в репо. Итак, извлеченный урок: проверьте, на каком репо вы смотрите, прежде чем волноваться.

James Harrington
16 дек. 2014, в 18:34

Поделиться

У меня такая же проблема, потому что я использовал git clone --depth=1, что подразумевает --single-branch.

Выполняет завершенный git clone.

Huachao Huang
25 авг. 2016, в 12:08

Поделиться

Во-первых, проверьте родительскую ветвь. Затем введите

git fetch --all --prune 
git checkout <your branch>

Надеюсь, поможет!.

Shradhey Tripathi
09 авг. 2018, в 15:51

Поделиться

В ОС Windows по умолчанию git устанавливается

core.ignorecase = true

Это означает, что файлы git repo будут нечувствительны к регистру, чтобы изменить это, которое вам нужно выполнить:

yourLocalRepo> git config core.ignorecase false

эту конфигурацию можно найти в файле .gitconfig

Vasile Bors
11 окт. 2015, в 16:21

Поделиться

В моем случае у меня есть TWO branch 1) master (для живого сервера) 2) dev (тестовый сервер). Я установил несколько удаленных программ для ввода кода на соответствующем сервере. Когда я попытался переключить ветвь, я получил ошибку, например error: pathspec 'master' did not match any file(s) known to git.

Вы можете увидеть их на git remote -v.
Я удалил другой удаленный, кроме origin remote, с помощью git remote remove <remote-name>

Тогда git fetch

Теперь я могу проверить ветвь на git checkout <branch-name>.

ProCylon
10 дек. 2016, в 11:57

Поделиться

Если это происходит в Windows, это, вероятно, проблема с именем файла.

У меня была эта ошибка сегодня — я создал новый файл, добавленный в GIT, затем я сменил одну букву в имени файла с нижнего на верхний, а затем я ничего не мог — зафиксировать, вернуть, удалить файл из репо,

Единственное решение, которое я нашел, это снова изменить имя файла обратно в тот же самый случай, когда я добавил этот файл в GIT, а затем сделав GIT revert, чтобы удалить этот файл из GIT, а затем сменив имя файла снова, как я хочу, После этих изменений я мог бы выполнить репо, а затем нажать без проблем.

Marcin Nabiałek
03 март 2015, в 18:27

Поделиться

Произошло со мной после переименования незафиксированного файла в Android Studio.

У Git, похоже, была старая версия в своем хранилище, даже если ее больше не существовало.

fetch, pull, checkout, add all and so on did not help in my case!

Поэтому я открыл графический интерфейс Git TortoiseGit, который показал мне точный файл, вызвавший проблемы.

После этого я удалил файл из хранилища с помощью

git rm -r --cached /path/to/affected/file

и проблема исчезла

Marian Klühspies
25 март 2015, в 13:01

Поделиться

У меня была такая же проблема. Я думал, что у меня есть ветвь с именем foo, когда я пытаюсь:

git checkout foo

Я получал:

error: pathspec 'foo' did not match any file(s) known to git.

Затем я попробовал имя полной ветки:

git checkout feature/foo

тогда работал у меня.

tokhi
10 июнь 2013, в 09:54

Поделиться

Я сделал глупую ошибку, не указав флаг -m во время совершения (lol)

git commit -m "commit message in here"

Ajain Vivek
23 март 2017, в 14:25

Поделиться

в моем случае я вхожу в каталог подмодулей, не делая

  • git submodule init
  • git submodule update

Итак, git был связан с родительской папкой, которая действительно пропустила эту ветвь.

Ilya Gazman
26 авг. 2015, в 13:12

Поделиться

Ни один из этих ответов не решил мою проблему:

[email protected] ~/Documents/NetBeansProjects/Version (master)
$ git log --format=oneline
b9cc6a9078312865280fb5432a43e17eff03a5c6 Formatted README
288772f36befe6bd60dd41b8185f1e24e0119668 Updated README documentation
d2bdbe18f4169358d46fad50eacfb89786df3bf8 Version object v3.0.0-SNAPSHOT
a46b1910a3f548b4fa254a6055d25f68d3f217dd VersionFactory is now Platform agnostic
24179ae569ec7bd28311389c0a7a85ea7b4f9594 Added internal.Platform abstraction
252b684417cf4edd71aed43a15da2c8a59c629a7 Added IPlugin implementation for Sponge
e3f8d21d6cf61ee4fc806791689c984c149b45e3 Added IPlugin implementation for Bukkit
aeb403914310b4b10dee9e980cf64472e2bfda79 Refactored Version.java
ef50efcff700c6438d57f70fac30846de2747a7e Refactored TesterFactory
a20808065878d4d28657ae362235c837cfa8e625 Added IPlugin abstraction
9712a3575a70060d7ecea8b62bb5e888fdc32d07 Heavily refactored Tester
02d025788ae740dbfe3ef76a132cea8ca4e47467 Added generic Predicate<T> interface
9c565777abea9be6767dfdab4ab94ed1173750dd Minor refactoring of testCompareTo()
2ff2a28c221681e256dcff28770782736d3a796a Version object v2.0.1
d4b2e2bd830f77cdbc2297112c2e46b6555d4393 Fix compareTo()
05fe7e012b07d1a5b8de29804f96d9a6b24229a1 Make compareTo() fail
6e85371414357a41c1fc0cec0e75adba92f96832 Fix VersionFactory passing null
c1fd1f032f87d860d5ed9d6f6679c9fa522cff8d Version object v2.0
62c3a92c008a2ed11f0a4d016080afc3541d0700 Version object v1.2
c42e9e617128085e872c51b4d977a04e48d69e8f Deprecated, doc'd, future-proofed getNm


[email protected] ~/Documents/NetBeansProjects/Version (master)
$ git checkout 3a796a
error: pathspec '3a796a' did not match any file(s) known to git.

Я пытался вернуться и построить фиксацию для Version object v2.0.1. К счастью, у меня возникла идея попробовать весь хеш-код, и это сработало! Это означает, что я использовал неправильный конец хэш-кода.

[email protected] ~/Documents/NetBeansProjects/Version (master)
$ git checkout 2ff2a
Note: checking out '2ff2a'.

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 performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at 2ff2a28... Version object v2.0.1

[email protected] ~/Documents/NetBeansProjects/Version ((2ff2a28...))
$

Как показано выше, для частичных хеш-кодов вы должны предоставить интерфейс, а не внешний.

Nikolaii99
05 авг. 2015, в 23:30

Поделиться

В моем случае я переименовал файл, изменяющий случай файла, т.е. SomeFile.js → someFile.js

Я думаю, что это было связано с проблемой. Выполнение git fetch не помогло решить проблему.

Я вытащил файлы из своего проекта, сделал выборку и без толчка. Затем я сделал выборку, добавил их обратно и сделал толчок, и это сработало. Я не знаю, нужны ли все эти шаги, но это в конечном итоге сработало.

Kip
31 март 2015, в 23:51

Поделиться

Я скопировал url удаленного источника из другого файла .git/config, поэтому в моем новом файле .git/config отсутствовала следующая строка в разделе [remote "origin"]

fetch = +refs/heads/*:refs/remotes/origin/*

Добавление вышеуказанной строки исправило error: pathspec 'master' did not match any file(s) known to git.

AamirR
09 дек. 2018, в 16:55

Поделиться

Для меня это была проблема с моими полномочиями


Попробовав некоторые ответы, один из них помог мне решить проблему:

Запустив git fetch выдал следующую ошибку:

Не удалось разрешить хост: bitbucket.org

Все, что мне нужно было сделать, это заставить мою IDE (VS Code в моем случае) запомнить мои учетные данные:

git config --global credential.helper wincred

Git немедленно синхронизировал все изменения, и git checkout <branche> теперь работает нормально!

Jeffrey Roosendaal
30 авг. 2018, в 19:13

Поделиться

Я столкнулся с этой же проблемой, когда я впервые играл с git. При попытке моего первого совершения…

git commit -m 'first commit!'

Я получил ошибку, упомянутую OP…

error: pathspec 'commit!'' did not match any file(s) known to git.

Я думал, что, возможно, запутался git, используя ключевое слово в сообщении commit, поэтому я попробовал несколько других слов и получил ту же ошибку.

Наконец, я использовал двойные кавычки в сообщении…

git commit -m "first commit!"

Это оказалось успешным…

[master (root commit) 0000000] first commit!
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 dummyDoc.txt

TheLastGIS
28 дек. 2016, в 00:44

Поделиться

Хорошо, ответов уже слишком много. Но в моем случае я столкнулся с этой проблемой, когда работал над Eclipse и использовал git-bash для переключения между ветками/извлечениями. Как только я закрыл затмение и перезапустил git-bash для проверки, все работало хорошо.

Поэтому я предлагаю вам дважды проверить, не используется ли ваш репозиторий другим приложением.

Mohammad Faisal
12 сен. 2018, в 16:46

Поделиться

Одна возможная причина. Если вы работаете с машиной Windows с MINGW *

ISSUE

Проверьте имя ветки, которую вы хотите проверить. Windows опускает символ ' из имени ветки во время разбора команды.

например: если у вас есть имя ветки, например bugfix/some-'branch'-name

Когда вы выдаете команду: > git checkout bugfix/some-'branch'-name, она будет анализировать ее как bugfix/some-branch-name, заметьте, что она пропускает символ '.

REMEDY

Чтобы проверить это имя ветки, добавить escape-символ при выдаче команды.

Тип: > git checkout bugfix/some-'branch'-name

Затем он работает!!

Piyush Sagar
19 окт. 2016, в 12:51

Поделиться

В моем случае я запускаю «git fetch» до «git branch…:, но получил ту же ошибку.
Затем я проанализировал его и нашел ошибку в имени моей ветки. Исправлено и успешно переключилось на ветвь.

Viktor Chmel
19 июль 2016, в 10:34

Поделиться

Я столкнулся с этой проблемой в прошлый раз, и то, что я сделал, это удалить папку (или исходный код), связанную с этой веткой.

Ex: начало ветки /foo создает папку foo на вашем локальном, поэтому я просто удаляю ее и использую git fetch $ checkout, чтобы получить код с удаленного.

Или вы можете сделать это, создав папку на том же месте, что и ветка, которую вы планировали проверить.

Ex: создайте папку foo на локальном компьютере, после этого используйте команду Git: git branch --set-upstream-to=origin/foo foo, что все. Используйте git pull для получения кода.

blackberry
25 янв. 2016, в 05:17

Поделиться

У меня была эта проблема при работе с Git в Windows. В моем случае это была проблема.
Я уже добавил и перенял файл в мой репозиторий, а потом изменил только его случай.
Чтобы решить проблему, я переименовал файл в соответствии с исходным случаем и снова переименовал его с помощью команды git mv. По-видимому, это позволяет Git отслеживать переименование.

Примечание. Я использовал Cygwin.

Thomas Eizinger
16 сен. 2015, в 15:42

Поделиться

Я столкнулся с подобной проблемой. Что привело меня в эту беду:
У меня было несколько удаленных веток, и я удалил папку с кодом.
Я потянулся.:

git pull [email protected]

Затем я добавил удаленный репозиторий:

git remote add upstream [email protected]

Затем я попытался изменить ветвь на другую ветку, скажем, AAAA, и я получил ошибку

error: pathspec 'AAAA' did not match any file(s) known to git.

Проведя час, я нашел решение.
Я снова удалил исходную папку.
Затем я сделал git pull:

git pull [email protected]

Затем я изменил ветвь, прежде чем связывать ее с удаленным репозиторием:

git checkout AAA

то я добавил его в удаленный репозиторий

git remote add upstream [email protected]

После этого я могу легко переключать ветки.
Хотя это не стандартный способ, но он работал у меня после того, как я попробовал все вышеперечисленные варианты.

Amit Kumar
29 окт. 2014, в 11:21

Поделиться

Это может быть вызвано тем, что восходящий поток перезаписывает историю.

Когда это произойдет, я бросаю все затронутые репозитории, клонирую их свежими из восходящего потока и использую ‘git format-patch’/’git am’, чтобы переправлять любые выполняемые работы из старого мира в новый.

Dan Kegel
14 март 2014, в 00:27

Поделиться

Я получил тот же pathspec error на git — bash. Я использовал Tortoise git в окнах для переключения/проверки ветки.

nouveau
17 апр. 2013, в 09:08

Поделиться

У меня была та же проблема (с версией git-latest) и я обнаружил, что это связано с кодами escape-цветов, используемыми git. Интересно, может ли это объяснить, почему эта проблема возникает так часто.

Это демонстрирует, что может происходить, хотя цвет обычно задается в конфигурации git, а не в командной строке (в противном случае это будет очевидно):

~/dev/trunk (master)$ git checkout 'git branch -l  --color=always  | grep django-1.11'
error: pathspec 'django-1.11' did not match any file(s) known to git.
~/dev/trunk (master)$ git branch -l  --color=always  | grep django-1.11
  django-1.11
~/dev/trunk (master)$ git checkout 'git branch -l  | grep django-1.11'
Switched to branch 'django-1.11'
Your branch is up-to-date with 'gerrit/django-1.11'.
~/dev/trunk (django-1.11)$ 

Я полагаю, что git-конфигурация, которая не играет с настройками цвета, должна работать color = auto должна делать правильные вещи. Моя конкретная проблема заключалась в том, что git recent я использовал, был определен как псевдоним с жестко закодированными цветами, и я пытался создавать команды поверх этого.

Danimal
27 июль 2018, в 14:03

Поделиться

Я получил это на столе Github после нажатия «Обновить из…», когда было выбрано неправильное репо. Затем я изменил репо на правильный, но когда я попытался удалить изменения, я получил эту ошибку. Это потому, что это были новые файлы в репо, которые я ошибочно выбрал, но не тот, который я хотел обновить.

Я просто сменил селектор репо на тот, который я неправильно выбрал в первый раз, после чего смог удалить изменения.

Затем я сменил селектор репо на тот, который я хотел.

user2568374
24 авг. 2015, в 14:37

Поделиться

$ cat .git/refs/heads/feature/user_controlled_site_layouts
3af84fcf1508c44013844dcd0998a14e61455034

Можете ли вы подтвердить, что следующие работы:

$ git show 3af84fcf1508c44013844dcd0998a14e61455034

Возможно, кто-то переписал историю и что это обязательство больше не существует (по какой-либо причине).

ralphtheninja
13 май 2011, в 12:28

Поделиться

Это случилось со мной также в Windows на двух локальных ветких, которые я создал сам.
После выхода из ветки я не смог проверить

bugfix_ # 303_multiline_opmerkingen_not_displaying_correctly_in_viewer

и

bugfix_339_hidden_fields_still_validated

вы можете увидеть на скриншоте из Git bash ниже.

Изображение 7704

Когда я попытался использовать графический интерфейс Git, я даже не мог видеть ветки вообще. Однако, когда я использовал инструмент Pycharms Git, я увидел это:

Изображение 7705

Итак, почему-то окна решили добавить некоторую неразличимую персонаж к моим именам ветвей, и именно по этой причине это не сработало. Переименование ветвей в Pycharm сделал трюк, поэтому угадайте, что это будет работать и на других IDE.

tarikki
01 июнь 2016, в 07:08

Поделиться

Вот как я решил свою ошибку!

Сначала я удалил свое репо локально, а также из моего Github. Затем я раздвоил и клонировал в свой локальный репозиторий.

После этого я сделал свое изменение и наконец

Создана Моя ветка с помощью

$git checkout -b moh_branch

изменить рабочую ветвь

$git checkout moh_branch

нажмите ветку на GitHub

$git push origin moh_branch

После этого я могу выполнить свои изменения следующим образом: —

$git add .

$git commit -m "updated readme.md"

$git push origin moh_branch

Премию 100% для меня!!

Moh K
30 авг. 2017, в 17:19

Поделиться

Поскольку ваша ветвь функции существует в удаленном режиме, это повреждает локальное репо. Итак, удалите локальное репо и повторите клонирование. Теперь ‘git checkout <branch_name>‘ должен работать для вас.

Ninos
18 апр. 2017, в 19:07

Поделиться

Это сработало для меня. Он отбрасывает все локальные изменения и сбрасывает их до последнего фиксации.

git reset --hard

timbo7io
21 янв. 2017, в 02:28

Поделиться

Если вы находитесь в Windows, вы, вероятно, можете изменить имя файла на нижний/верхний регистр, например File.txt — file.txt

Итак, проверьте, какой файл у вас есть в git и переименуйте его в нужное вам:

git status

Затем мне нужен файл file.txt → but git, который дает мне файл File.txt, поэтому просто переименуйте его

git mv File.txt file.txt

И проблема решена.

Manic Depression
07 июль 2017, в 19:04

Поделиться

Ещё вопросы

  • 1запрос объяснения различий в поведении bw VB6 и C # CryptAcquireContext
  • 0Доктрина ODM MongoDB — ReferenceOne против ReferenceMany
  • 0jQuery Mobile настройки Иконки для кнопок
  • 1Cloudant слушатель базы данных в python
  • 0Что делает эта функция? Что-то делать с фиксированными значениями?
  • 0Бинарное дерево поиска обнаруживает ошибки в незнакомом месте
  • 0Эмулятор пульсаций, выдающий 404 для локального файла
  • 1Создайте словарь подсчета категорий для столбца панд
  • 0скрытие элемента на размытие, когда оно показано
  • 0Переопределить изображения, получая высоту + ширину из CSS, вместо этого атрибут html
  • 0Структура папок / файлов ZEND Framework
  • 0Добавить стили в пользовательское меню
  • 1Значение шифрования Java не соответствует значению шифрования javascript
  • 1Есть ли способ ввести переменную шага огурца из области действия сценария в cucmber?
  • 1Использование классов в цикле for в node.js
  • 1Каковы оптимальные методы для быстрого ввода-вывода на медленных соединениях?
  • 0Два способа вызвать исключение в C ++ (без использования кучи)
  • 0Сохранение контекста при использовании jQuery.on
  • 1Как сделать цилиндр в Renderscript
  • 1Разбейте строку и получите конкретную строку
  • 1Не удается сохранить дату календаря в базе данных в Java
  • 1Не удается создать нового пользователя с помощью поставщика внешней аутентификации в Web API (обновление 2 для Visual Studio 2013)
  • 0Как непрерывно запускать скрипт PHP на сервере виртуального хоста?
  • 0Как добавить jQuery в шаблон Joomla?
  • 0curl не работает для «динамических моделей блогов»
  • 0Форматирование добавленного текста с использованием JavaScript
  • 0Показать на основе отметки времени
  • 0cec-клиент через php ничего не возвращает
  • 0Jquery переключить отображение перед анимацией?
  • 0Ошибка выполнения Jquery при использовании Datepicker
  • 1Динамическая маршрутизация с использованием колбы и Python не работает
  • 1phoneGap / разработка Titanium
  • 1Невозможно использовать ресурсы в производственном режиме с Tomcat
  • 0Как мне заставить инструмент разработчика также проверять всплывающее окно, созданное страницей?
  • 1Как закодировать пароль Jaysypt
  • 0Третья кнопка asp.net не открывает диалоговое окно jQuery
  • 0Mysql — Рекурсивный расчет баланса
  • 1Невозможно запустить очень простой COM-клиент
  • 0увеличить размер стека в затмении CDT?
  • 1Определение свойств UserControl и их привязка в Windows Phone
  • 0Как выровнять на странице два приложенных ребенка, JavaScript
  • 1OutOfMemoryError в галактике s3
  • 0получить центр обнаруженного круга в изображении / opencv / c ++
  • 0Применение css n-го потомка к угловому сгенерированному html
  • 0Пользовательский диалог javascript / jquery в мобильном приложении не отображается
  • 1Используя аналитику Google, возможно ли создать пользовательское измерение с помощью API (программно)
  • 0PHP dataURL в изображение png
  • 1Javascript для цикла, не ожидающего выполнения всех обещаний
  • 1Vue Webpack Build Breaks Bulma CSS
  • 1Запуск исполняемых файлов из Java

Сообщество Overcoder

I just installed Git on Windows XP Pro and I’m trying to apply it to my project.

I’m trying git-ize a legacy directory structure:

C:src>git init
C:src>git add *.c
C:src>git commit -m 'initial project version'
error: pathspec 'project' did not match any file(s) known to git.
error: pathspec 'version'' did not match any file(s) known to git.

Any ideas what the problem could be? What does this error mean?

«git status» displays many «new file:» lines so I don’t know why it says it doesn’t match anything.

asked Jun 25, 2010 at 14:58

Pete Alvin's user avatar

Try using double quotes for «Initial project version»

answered Jun 25, 2010 at 15:27

Pylsa's user avatar

PylsaPylsa

30.4k16 gold badges88 silver badges116 bronze badges

1

I had the same problem and the answer from BloodPhilia worked!

I just wanted to move one of my projects to the GitHub, so I just copied commands from my GitHub repository setup:

git init
touch README
git add README
git commit -m 'first commit'
git remote add origin https://github.com/YuriyHorobey/lp.git
git push -u origin master

(touch will not work under Windows, just create a README file) and this one had failed:

git commit -m 'first commit'

I’ve replaced ' with " and it works!

Gaff's user avatar

Gaff

18.3k15 gold badges56 silver badges68 bronze badges

answered Jul 19, 2012 at 6:44

Yuriy's user avatar

YuriyYuriy

212 bronze badges

Понравилась статья? Поделить с друзьями:
  • Did not connect potential security issue как исправить
  • Dictionary problem vmware как исправить
  • Dict object is not callable как исправить
  • Diarization error rate
  • Diameter error codes