Fatal pathspec did not match any files ошибка

I added over 9000 photos by accident to my project folder. And committed them. Then deleted them from disk. Committed.

Now I try to push changes to git server. But it takes too long and tries to send 12 Gb of data.

I checked files size on disk and see that really .git folder takes 12 Gb.

How to delete photos from there? I tried git rm, but fails:

❯ git rm public/photos
fatal: pathspec 'public/photos' did not match any files

Because I allready deleted them from disk, but they are still in .git folder.

I tried to add public/photos to .gitignore:

public/photos/
*.zip

But no result.
Of course I could hard reset head to moment when I did not have so many junk photos in my project. But since that time i committed many times and made a lot changes in code.

David Parks's user avatar

David Parks

30.7k47 gold badges185 silver badges328 bronze badges

asked Aug 23, 2014 at 4:00

Maxim Yefremov's user avatar

Maxim YefremovMaxim Yefremov

13.7k27 gold badges118 silver badges166 bronze badges

In your case, use git filter-branch instead of git rm.

git rm will delete the files in the sense that they will not be tracked by git anymore, but that does not remove the old commit objects corresponding to those images, and so you will still be stuck with pushing the earlier commits which correspond to 12GB of images.

The git filter-branch, on the other hand, can remove those files from all the previous commits as well, thus doing away with the need to push any of them.

  1. Use the command

    git filter-branch --force --index-filter \
      'git rm -r --cached --ignore-unmatch public/photos' \
      --prune-empty --tag-name-filter cat -- --all
    
  2. After the filter branch is complete, verify that no unintended file was lost.

  3. Now add a .gitignore rule

    echo public/photos >> .gitignore
    git add .gitignore && git commit -m "ignore rule for photos"
    
  4. Now do a push

    git push -f origin branch
    

Check this, this and this for further help. Just to be on the safer side, I would suggest you create a backup copy of the repo on your system before going ahead with these instructions.

As for your orignial error message, it is happening because you already untracked them using git rm, and hence git is complaining because it can’t remove a file it isn’t tracking. Read more about this here.

Community's user avatar

answered Aug 23, 2014 at 4:40

Anshul Goyal's user avatar

Anshul GoyalAnshul Goyal

73.4k37 gold badges150 silver badges186 bronze badges

10

A very simple answer is.

Step 1:

Firstly add your untracked files to which you want to delete:

using git add . or git add <filename>.

Step 2:

Then delete them easily using command git rm -f <filename> here rm=remove and -f=forcely.

answered Oct 20, 2016 at 11:13

Bharti Rawat's user avatar

2

Step 1

Add the file name(s) to your .gitignore file.

Step 2

git filter-branch --force --index-filter \
    'git rm -r --cached --ignore-unmatch YOURFILE' \
    --prune-empty --tag-name-filter cat -- --all

Step 3

git push -f origin branch

A big thank you to @mu.

Will's user avatar

Will

24.1k14 gold badges97 silver badges108 bronze badges

answered Jun 4, 2016 at 3:01

klmlfl's user avatar

klmlflklmlfl

4314 silver badges5 bronze badges

2

To remove the tracked and old committed file from git you can use the below command. Here in my case, I want to untrack and remove all the file from dist directory.

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch dist' --tag-name-filter cat -- --all

Then, you need to add it into your .gitignore so it won’t be tracked further.

answered Sep 18, 2019 at 7:18

Kiran Maniya's user avatar

Kiran ManiyaKiran Maniya

8,50110 gold badges58 silver badges81 bronze badges

3

using this worked for me

git rm -f --cached <filename>

answered Jan 12, 2020 at 17:49

Andreia Oliveira's user avatar

Sometimes it’s happens when you are not tracking your file add your file with git add untracked file name, after this simply do git rm -r file name

answered Jun 18, 2021 at 13:15

Vakho Jgenti's user avatar

git stash 

did the job,
It restored the files that I had deleted using rm instead of git rm.

I did first a checkout of the last hash, but I do not believe it is required.

answered May 28, 2018 at 15:36

user1767316's user avatar

user1767316user1767316

3,2743 gold badges37 silver badges46 bronze badges

This chains work in my case:

  1. git rm -r WebApplication/packages

There was a confirmation git-dialog. You should choose «y» option.

  1. git commit -m "blabla"
  2. git push -f origin <ur_branch>

Daniel Puiu's user avatar

Daniel Puiu

9626 gold badges21 silver badges29 bronze badges

answered Jun 4, 2018 at 13:35

Ustin's user avatar

UstinUstin

5686 silver badges19 bronze badges

Just for reference, I noticed that I had some files with permissions 000, maybe they were created with sudo , I don’t know, but after changing your permissions to 644 (I needed sudo for this operation), the problem was solved

sudo chmod 644 vendor/symfony/yaml

and the commit result :

diff --git a/vendor/symfony/yaml b/vendor/symfony/yaml
deleted file mode 160000
index 212a27b7..00000000
--- a/vendor/symfony/yaml
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 212a27b731e5bfb735679d1ffaac82bd6a1dc996
diff --git a/vendor/symfony/yaml b/vendor/symfony/yaml
new file mode 100644
index 00000000..20a0b9d0
--- /dev/null
+++ b/vendor/symfony/yaml
@@ -0,0 +1 @@
+Subproject commit 212a27b731e5bfb735679d1ffaac82bd6a1dc996

answered Apr 29, 2021 at 10:39

Sérgio's user avatar

SérgioSérgio

6,9661 gold badge48 silver badges53 bronze badges

I got the same error while I wanted to delete cached node_modules dir.

instead of
git rm -r -f --cached node_modules I had to use
git rm -r -f --cached **/node_modules, because the dir was not part of the root dir.

answered Oct 14, 2022 at 7:25

Alex Szücs's user avatar

Alex SzücsAlex Szücs

5615 silver badges12 bronze badges

I had this error when I aborted an upload which was taking too long, to fix it I renamed the file, commit, renamed it back, commit.

answered May 24 at 8:35

7RedBits.com's user avatar

I had a similar issue with the following error message (Google brought me here):

error: pathspec 'elements (conflicted copy 2013-08-06)' did not match any file(s) known to git

I tried all of the solutions described here, but none worked for me.
I had two files that were simply not there anymore, but git was still showing me the files and it was impossible to remove them. They were created thanks to a conflict with Dropbox.

Steps that worked for me:

  1. git stash

This resulted in the two files existing again in the folder

  1. rename the files to something else

Git will now show the renamed files as untracked, but the old files still as deleted

Changes not staged for commit: (use «git add/rm …» to update
what will be committed) (use «git restore …» to discard
changes in working directory)
deleted: «elements (conflicted copy 2013-08-06)»
deleted: «layout (conflicted copy 2013-08-06)»

Untracked files: (use «git add …» to include in what will be
committed)
elements_dupe
layout_dupe

  1. git add -A

Suddenly, git status displayed, that the previous files were renamed

Changes to be committed:
(use «git restore —staged …» to unstage)

renamed: «elements (conflicted copy 2013-08-06)» -> elements_dupe
renamed: «layout (conflicted copy 2013-08-06)» -> layout_dupe

  1. git commit -m 'renamed duplicate files'

Afterwards, it was very easy to remove them by simply deleting the files and commit again.

answered Jun 16 at 9:43

gorkem's user avatar

gorkemgorkem

5006 silver badges8 bronze badges

I had a duplicate directory (~web/web) and it removed the nested duplicate when I ran rm -rf web while inside the first web folder.

answered Nov 13, 2019 at 23:20

ccsinsf's user avatar

1

I have some trouble with a git repository of mine and I cant find the error :(

Thing is, I had this repository already in use for a PHP project. everything was fine. Then, I «added» composer to it. I.e., I copied the composer file to the repositorie’s root, created a composer.json, and used «composer install». Hence, composer.lock and vendor/ were created for me.

Since I didnt want those to be included in the repo, I added the following to the .gitignore

composer
composer.lock
vendor/

Now, whenever I use «git add» oder «git commit» from the root, I will get the following errors:

$ git commit * -m "fixed issue #123"
error: pathspec 'composer' did not match any file(s) known to git.
error: pathspec 'composer.lock' did not match any file(s) known to git.
error: pathspec 'vendor' did not match any file(s) known to git.

Obviously, the commit (or add) does not work so I have to manually specify files to add or commit. Bummer.

I cannot find the problem :( Anyone knows how to fix this?

BTW I am using git version 2.4.9 (Apple Git-60)

➜  /myrepo git:(master) git add index.html

fatal: pathspec 'index.html' did not match any files

If you are trying to add a file to staging area using git command and you get the fatal pathspec did not match any files error, well reason could be one of the below,

  1. The file that you are trying to add to the staging area does not exist.
  2. You have misspelled the filename.
  3. You are in the wrong branch.

fatal pathspec did not match any files - git error

You can run the git staus command to check if the file exists or the correct name of the file in the untracked list of files,

➜  /myrepo git:(master) ✗ git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	sample.txt

nothing added to commit but untracked files present (use "git add" to track)

Facing issues? Have Questions? Post them here! I am happy to answer!

Я только начал изучать GIT. Следуйте их учебнику.

Теперь в самом начале я застрял с этой ошибкой:

Fatal: pathspec 'file.txt' did not match any files.

Вот скриншот моей процедуры и команд:

введите описание изображения здесь

Что я здесь не так делаю?

2013-11-25 08:52

17
ответов

Файлы не существуют, поэтому они не могут быть добавлены. Убедитесь, что файлы были созданы первыми.

D:\temp\hi>git init
Initialized empty Git repository in D:/temp/hi/.git/

D:\temp\hi>dir
 Volume in drive D is Data
 Volume Serial Number is 744F-7845

 Directory of D:\temp\hi

2013-11-25  12:59 AM    <DIR>          .
2013-11-25  12:59 AM    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  1,331,387,256,832 bytes free

D:\temp\hi>git add hi.txt
fatal: pathspec 'hi.txt' did not match any files

D:\temp\hi>echo hello > hi.txt

D:\temp\hi>git add hi.txt

D:\temp\hi>dir
 Volume in drive D is Data
 Volume Serial Number is 744F-7845

 Directory of D:\temp\hi

2013-11-25  12:59 AM    <DIR>          .
2013-11-25  12:59 AM    <DIR>          ..
2013-11-25  12:59 AM                 8 hi.txt
               1 File(s)              8 bytes
               2 Dir(s)  1,331,387,256,832 bytes free

2013-11-25 09:01

Я делал:

git add AppName/View Controllers/Sections/Devices/DeviceContainerViewController.swift

Но возникла следующая ошибка:

фатальный: pathspec ‘AppName/View’ не соответствует ни одному файлу

Как видите, команда прерывается между представлением и контроллерами, потому что есть пробел.

Мне просто пришлось заключить свой путь в двойные кавычки. Обычно в этом нет необходимости, но когда у вас есть пробелы, вам нужно.

git add "AppName/View Controllers/Sections/Devices/DeviceContainerViewController.swift"

2019-04-18 23:11

Чтобы добавить файл в git, он должен существовать. git add не создает файл, но говорит git добавить его в текущую ветку и отслеживать его.

В настоящее время у вас нет отслеживаемых файлов, как вы можете видеть из своего git status команда. Чтобы отследить все файлы из каталога my-project, выполните git add my-project/*, Это добавит все файлы из этого каталога.

Далее, если у вас нет нужного file.txt, просто создайте текстовый файл и запустите git status, Он должен показать вам, что у вас есть неотслеживаемый файл file.txt, который вы можете впоследствии добавить в git, используя git add file.txt,

2013-11-25 09:16

Примечание: вы не должны видеть это конкретное сообщение об ошибке в git 1.9/2.0 (первый квартал 2014 года).

Смотрите коммит 64ed07c Нгуен Тхай Нгук Дуй ( pclouds ):

add: не жалуйтесь при добавлении пустого корня проекта

Такое поведение было добавлено в 07d7bed (add: не жалуйтесь при добавлении пустого корня проекта — 2009-04-28, git 1.6.3.2)
затем сломанный 84b8b5d (удалить match_pathspec() в пользу match_pathspec_depth() — 2013-07-14, git 1.8.5).

Восстановите это.


Идея заключается в следующем:

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

К сожалению, file_exists() Тест был прерван для одного особого случая: путь к корню проекта просто «».
Этот патч обнаруживает этот особый случай и действует так, как будто файл существует (что он и должен делать, поскольку он является корнем проекта).

Эффект, видимый пользователю, заключается в следующем:

$ mkdir repo && cd repo && git init && git add .

жаловался как:

fatal: pathspec '' did not match any files

но сейчас тихий неоператор.

Это снова тихий no-op в предстоящем git 1.9/2.0 (первый квартал 2014 года)


user6309

12 янв ’14 в 17:46
2014-01-12 17:46

2014-01-12 17:46

У меня была такая же проблема, потому что к имени файла уже добавлено.txt, а вы явно добавляете дополнительный.txt. Вы можете попробовать это:

git add file.txt.txt

2018-06-16 12:20

Чтобы добавить файл в git, он должен существовать. git add не создает файл, но говорит git добавить его в текущую ветку и отслеживать его. Таким образом, вы должны создать новый файл в командной строке:

MD <new file>

После этого вы добавляете:

git add <new file> 

2018-06-06 14:47

Просто укажите путь к файлу при добавлении файла в команду git add, у меня это работает

$ git add mainFolder/…/file.extension

Примечание: mainFolder будет папкой внутри вашего репо.

2020-09-07 13:21

Упомяните путь правильно. Вам не нужно никаких кавычек.

Правильный путь будет,

git add /path/path/filename.txt

2017-11-17 12:57

Я сделал то же самое, что и Дэвид Чой (вверху). Я переместил свой файл в правильный каталог, затем щелкнул и перетащил его ниже, и после того, как мой файл изменил статус на «неотслеживаемый», я мог ввести команду «git add», чтобы оставаться отслеживаемым.



04 ноя ’21 в 22:27
2021-11-04 22:27

2021-11-04 22:27

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

сначала создайте файл.txt и правильно укажите путь! пусть есть

$ git add path/filename.txt

(Не для этого, для любой команды git для изменения промежуточной области запишите полный путь к имени файла с косой чертой после команды)

например-

если ваш файл находится на рабочем столе, то

$ git add C:Users/username/Desktop/filename.txt

2018-12-13 19:52

Я тоже застрял над этим. Решение: а) сначала создайте любой текстовый файл, скажем, » Readme.txt «

б) Скопируйте этот текстовый файл в ваше локальное git-репо (папку), например, C: / store

c) Перейдите в командную строку Windows, если вы находитесь в Windows (введите » cmd » в строке поиска, когда вы нажимаете на кнопку окна)

г) зайдите в местное git-репо. введите ** echo hello> Readme.txt ** —> C: \ admin \ store> echo hello> Readme.txt

echo hello — команда dos, которая показывает текст состояния вывода на экран или в файл.

2017-12-03 07:34

У меня была такая же проблема. Подтвердите каталог с файлами. После перемещения моего файла в правильный каталог он работает.

git output

2020-05-08 05:04

У меня была такая же проблема, но с файловой системой Windows. Вот мое решение, которое сработало.

из каталога проекта git. Вот именно то, что отображалось в текущем каталоге.

D: \ Projects \ ReactNative \ project>git add «scr / \ components / \ validate.js»

В git вводится файл validate.js. Он находился в каталоге проекта. Этот каталог был src \ components.

2020-01-15 21:08

Ну вот! Очень простой. Необходимо вручную поместить файл.txt в указанную папку pwd…

suumapat @SUUMAPAT-IN MINGW64 ~ / newproject (master)$ git add abc.txt фатальный: pathspec ‘abc.txt’ не соответствует ни одному файлу

suumapat @SUUMAPAT-IN MINGW64 ~ / newproject (master)$ dir

suumapat @SUUMAPAT-IN MINGW64 ~ / newproject (мастер)$ pwd / c / Users / suumapat / newproject

suumapat @SUUMAPAT-IN MINGW64 ~ / newproject (master)$ dir abc.txt

suumapat @SUUMAPAT-IN MINGW64 ~ / newproject (master)$ git add abc.txt

2020-01-01 15:14

Эта ошибка возникает из-за того, что файл, который вы добавляете в репозиторий, не создается. Сначала создайте файл, а затем добавьте его в область подготовки:

touch filename
git add filename

2020-09-28 18:39

Прежде чем запускать команду «git add file.txt»,

входить:

эхо-файл > файл.txt

Затем инициируйте команду:

git добавить файл .txt

Это сработало для меня.

2023-01-26 22:18

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

Ошибка:

      fatal: pathspec 'index.html' did not match any files

Решение:

      git add "file_name"

2020-12-30 09:55

Другие вопросы по тегам
git

Most developers deal with multiple errors while working on Git. More specifically, the “error: pathspec ‘…’ did not match any file(s) known to git’” error mostly occurs when the specified branch name does not exist in the list of branches. To resolve this error, they need to create and switch the specified branch first with the help of the “git checkout -b <branch-name>” command.

This guide will explain about:

  • When Does “error: pathspec ‘…’ did not match any file(s) known to git” Occur?
  • How to Resolve the “error: pathspec ‘…’ did not match any file(s) known to git” Error?

To mention error encountered mainly by developers when they want to access a branch that does not exist in the local branch.

How to Resolve the “error: pathspec ‘…’ did not match any file(s) known to git” Error?

To resolve the above-stated error, developers are required to create the particular branch first and then switch to it by utilizing the “git checkout -b <branch-name>” command. Follow the below-stated steps to view the cause of the previously discussed error and then resolve it.

Step 1: Navigate to Git Root Directory
First, go to the Git root directory by executing the cd“ command:

$ cd «C:\Users\nazma\Git»

Step 2: Checkout to Local Branch
Then, run the “git checkout” command to switch to the desired local branch:

Here, the “beta” is the name of the local branch. However, it shows the “pathspec ‘betadid not match any file(s) known to git” error, which means the specified branch does not exist in the list:

To resolve the above-stated error, users need to create a new branch first.

Step 3: Generate and Switch Branch
To create and immediately navigate to the specified branch through the following command:

In the above-listed command, the “-b” option represents the branch:

According to the below-provided output, the new branch is generated and switched successfully.

Step 4: Verify Newly Created Branch
Lastly, to ensure whether the new branch is created or not, run the following command:

As you can see, the new branch exists in the list of local repositories:

That’s all! We have provided the solution for the discussed error.

Conclusion

To “pathspec ‘…’ did not match any file(s) known to git” error occurs when users want to access the branch which does not exist in the local branch. To resolve this error, they need to execute the “git checkout -b <branch-name>” command. This guide provided the easiest way to resolve the discussed pathspec error.

About the author

I hold a master’s degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.

Понравилась статья? Поделить с друзьями:
  • Fatal password authentication failed for user postgres ошибка
  • Fallout 76 ошибка идентификации как начать
  • Fallout 76 произошла неизвестная ошибка
  • Fallout 76 ошибка при создании учетной записи
  • Fallout 76 ошибка идентификации квест