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.5k18 gold badges159 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,9619 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.2m519 gold badges4346 silver badges5164 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,55512 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

3181 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 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)

Have Questions? Post them here!

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

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 ошибка как исправить
  • Fatal error ошибка рендеринга 0x00000007
  • Fatal error неисправимая ошибка пожалуйста перезапустите игру gta 5
  • Fatal error как исправить ошибку при запуске игры
  • Farming simulator 17 ошибка при запуске приложения 0xc0000022