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

I have just started learing GIT. Follow their tutorial.

Now at the very beginning I got stuck with this error:

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

Here is the screenshot of my procedure and commands:

enter image description here

What I am doing wrong here?

asked Nov 25, 2013 at 8:52

Hassan Sardar's user avatar

Hassan SardarHassan Sardar

4,38317 gold badges56 silver badges92 bronze badges

1

The files don’t exist, so they cannot be added. Make sure the files have been created first.

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

D:temphi>dir
 Volume in drive D is Data
 Volume Serial Number is 744F-7845

 Directory of D:temphi

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:temphi>git add hi.txt
fatal: pathspec 'hi.txt' did not match any files

D:temphi>echo hello > hi.txt

D:temphi>git add hi.txt

D:temphi>dir
 Volume in drive D is Data
 Volume Serial Number is 744F-7845

 Directory of D:temphi

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

answered Nov 25, 2013 at 9:01

chwarr's user avatar

0

I was doing:

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

But was getting the following error:

fatal: pathspec ‘AppName/View’ did not match any files

As you can see the command is breaking between View & Controllers because there’s a space.

I just had to wrap my path into double quotes. It’s not normally necessary, but when you have spaces you need to.

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

answered Apr 18, 2019 at 20:11

mfaani's user avatar

mfaanimfaani

32.6k18 gold badges160 silver badges287 bronze badges

1

In order to add a file to git it has to exist. git add does not create a file, but tells git to add it to the current branch you are on and track it.

Currently, you have no tracked files, as you can see from your git status command. In order to track all files from the my-project directory, do a git add my-project/*. This will add all the files from that directory.

Next, if you do not have the desired file.txt, just create a text file and run git status. It should show you that you have an untracked file.txt file, which you can afterwards add to git using git add file.txt.

answered Nov 25, 2013 at 9:16

Raul Rene's user avatar

Raul ReneRaul Rene

9,9719 gold badges53 silver badges75 bronze badges

Note: you shouldn’t see this particular error message in git 1.9/2.0 (Q1 2014).

See commit 64ed07c by Nguyễn Thái Ngọc Duy (pclouds):

add: don’t complain when adding empty project root

This behavior was added in 07d7bed (add: don’t complain when adding
empty project root — 2009-04-28, git 1.6.3.2)
then broken by 84b8b5d (remove match_pathspec() in favor of match_pathspec_depth() — 2013-07-14, git 1.8.5).

Reinstate it.


The idea is:

We try to warn the user if one of their pathspecs caused no matches, as it may have been a typo. However, we disable the warning if the pathspec points to an existing file, since
that means it is not a typo but simply an empty directory.

Unfortunately, the file_exists() test was broken for one special case: the pathspec of the project root is just «».
This patch detects this special case and acts as if the file exists (which it must, since it is the project root).

The user-visible effect is that this:

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

used to complain like:

fatal: pathspec '' did not match any files

but now is a silent no-op.

It is again a silent no-op in upcoming git 1.9/2.0 (Q1 2014)

answered Jan 12, 2014 at 17:46

VonC's user avatar

VonCVonC

1.2m523 gold badges4357 silver badges5179 bronze badges

I had the same problem because the file name is already appended with .txt and you are adding an extra .txt explicitly. You can try with this:

git add file.txt.txt

Robert's user avatar

Robert

5,27843 gold badges65 silver badges115 bronze badges

answered Jun 16, 2018 at 12:20

Siddharth's user avatar

In order to add a file to git it has to exist. git add does not create a file, but tells git to add it to the current branch you are on and track it. So you should create a new file in the command line :

MD <new file>

After that you add :

git add <new file> 

ascripter's user avatar

ascripter

5,56712 gold badges45 silver badges67 bronze badges

answered Jun 6, 2018 at 14:47

Aissa Amina's user avatar

Just give a file path while adding file to git add command, it works for me

$ git add mainFolder/…/file.extension

Note: mainFolder would be the folder inside your repo

answered Sep 7, 2020 at 10:21

iMRahib's user avatar

iMRahibiMRahib

5324 silver badges4 bronze badges

I was also stuck over this. The solution is :
a) Make any txt file first let’s say » Readme.txt «

b) Copy this text file to you local git repo(folder) eg- C:/store

c) Go to windows command prompt if you are on windows (type » cmd » on search bar when you click on window button )

d) go to your local git repo. type ** echo hello > Readme.txt**
—> C:adminstore>echo hello > Readme.txt

echo hello is a dos command which shows output status text to the screen or a file.

answered Dec 3, 2017 at 7:34

androminor's user avatar

androminorandrominor

3261 silver badge13 bronze badges

The file is not matched because git add creates your file in the root directory but it actually does not create a file, but tells git to add it to the current branch you are on (adds files from the working directory to the staging area) and track it with git status command. So,

first create the .txt file and mention the path correctly!
let there is

$ git add path/filename.txt

(Not for it only, for any git command for a change in staging area write the whole path of the filename with forwarding slash after the command )

e.g-

if your file is on the desktop then

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

answered Dec 13, 2018 at 19:52

Ashita Gaur's user avatar

Here you go! Very simple. Need to place the .txt file manually in the pwd mentioned folder…

suumapat@SUUMAPAT-IN MINGW64 ~/newproject (master)
$ git add abc.txt
fatal: pathspec ‘abc.txt’ did not match any files

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

suumapat@SUUMAPAT-IN MINGW64 ~/newproject (master)
$ pwd
/c/Users/suumapat/newproject

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

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

answered Jan 1, 2020 at 12:14

Suresh Dooly's user avatar

I was having the same issue but with the Windows file system. Here was my solution that worked.

from the git project directory. Here is exactly what was displayed with the current directory.

D:ProjectsReactNativeproject>git add «scr/components/validate.js»

The file being entered into git was validate.js. It was in a directory under the project. That directory was srccomponents.

answered Jan 15, 2020 at 18:08

David Hash's user avatar

David HashDavid Hash

871 silver badge8 bronze badges

I had the same issue as well. Please confirm your file directory.
After moving my file to the correct directory it works.

git output

ScheuNZ's user avatar

ScheuNZ

9118 silver badges19 bronze badges

answered May 8, 2020 at 2:04

David Choi's user avatar

This error is raised because the file you are adding to the repository is not created. First create the file and then add it to the staging area:

touch filename
git add filename

aalbagarcia's user avatar

answered Sep 28, 2020 at 15:39

Vishak k v's user avatar

Before initiating the command «git add file.txt»,

enter:

echo file > file.txt

Then initiate the command:

git add file.txt

This worked for me.

answered Jan 26 at 22:18

John Doe's user avatar

1

Use double quotes in the file name as shown below and it should work perfectly.

Error:

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

Solution:

git add "file_name"

Sabito stands with Ukraine's user avatar

answered Dec 30, 2020 at 6:55

Hillys's user avatar

2

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.5k47 gold badges183 silver badges327 bronze badges

asked Aug 23, 2014 at 4:00

Maxim Yefremov's user avatar

Maxim YefremovMaxim Yefremov

13.5k26 gold badges117 silver badges165 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

72.5k37 gold badges147 silver badges183 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

24k14 gold badges95 silver badges106 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,3359 gold badges55 silver badges80 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,2313 gold badges37 silver badges45 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

5586 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,9261 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

5515 silver badges10 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

4905 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

Git: невозможно проверить ветку — ошибка: pathspec ‘…’ не соответствует ни одному файлу (файлам), известным git

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

Вот в самом начале я застрял с такой ошибкой:

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

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

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

  • Не обязательно ваш случай, вы можете увидеть это с помощью git 1.8.5 на первом git add, в пустом репо. Это исправляется: см. Мой ответ ниже

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

D:temphi>git init Initialized empty Git repository in D:/temp/hi/.git/ D:temphi>dir Volume in drive D is Data Volume Serial Number is 744F-7845 Directory of D:temphi 2013-11-25 12:59 AM  . 2013-11-25 12:59 AM  .. 0 File(s) 0 bytes 2 Dir(s) 1,331,387,256,832 bytes free D:temphi>git add hi.txt fatal: pathspec 'hi.txt' did not match any files D:temphi>echo hello > hi.txt D:temphi>git add hi.txt D:temphi>dir Volume in drive D is Data Volume Serial Number is 744F-7845 Directory of D:temphi 2013-11-25 12:59 AM  . 2013-11-25 12:59 AM  .. 2013-11-25 12:59 AM 8 hi.txt 1 File(s) 8 bytes 2 Dir(s) 1,331,387,256,832 bytes free 

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

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

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

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

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

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

Это поведение было добавлено в 07d7bed (add: не жалуйтесь при добавлении пустого корня проекта — 28.04.2009, git 1.6.3.2)
затем сломан 84b8b5d (удалить match_pathspec() в пользу match_pathspec_depth() — 14.07.2013, git 1.8.5).

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


Идея такая:

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

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

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

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

раньше жаловался как:

fatal: pathspec '' did not match any files 

но теперь это тихий запрет.

В грядущем git 1.9 / 2.0 (первый квартал 2014 г.) это снова молчаливый отказ.

Я делал:

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

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

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

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

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

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

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

git add file.txt.txt 

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

MD  

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

git add  

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

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

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

г) перейдите в локальное репозиторий git. введите ** echo hello> Readme.txt ** —> C: admin store> echo hello> Readme.txt

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

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

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

$ git add path/filename.txt 

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

например-

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

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

Ну вот! Очень простой. Необходимо вручную поместить файл .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 (master) $ pwd / c / Users / suumapat / newproject

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

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

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

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

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

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

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

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

$ git add mainFolder /…/ file.extension

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

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

touch filename git add filename 

Tweet

Share

Link

Plus

Send

Send

Pin

➜  /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)

Have Questions? Post them here!

I am trying to remove a folder from my Git repository with

git rm folderToRemove

but Git issues this error when I try to do so.

fatal: pathspec 'siteFiles/applicationFiles/templates/folderToRemove' 
did not match any files

My current directory is «templates.» I am finding this error odd since I can cd into the folder «folderToRemove,» so it clearly exists. What does this error mean?

asked Jun 1, 2012 at 23:21

David Faux's user avatar

0

Git doesn’t version directories, only «content» (directory content or files)

did not match any files

That means there is no file to remove within folderToRemove, as I mention in «Unable to remove files recursively from Git».
You now can remove (Windows del or Unix rm) the directory itself.

As described in «Deleting empty directories in Git», you can also run a:

git clean -fd

However:

Warning: The clean command removes any files in the current working copy that aren’t being tracked by git. This is a good way to lose your work if you haven’t added new files to git. Always run git add before git clean.

Run rather first a:

git clean -d -x -n

As explained in «How do I clear my local working directory in git?».

Community's user avatar

answered Jun 1, 2012 at 23:39

VonC's user avatar

VonCVonC

14.4k5 gold badges46 silver badges60 bronze badges

3

  • Fatal metro exodus a crash has been detected by bugtrap как исправить ошибку
  • Faw j6 ошибка p01ef
  • Fatal int18 boot failure ошибка
  • Favostix brusko выдает ошибку
  • Fatal initialization failure torchlight 2 ошибка