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

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,33317 gold badges55 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

31.4k18 gold badges156 silver badges278 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,9139 gold badges52 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.2m508 gold badges4248 silver badges5069 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,26743 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,40512 gold badges49 silver badges66 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

3101 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

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

91110 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

За последние 24 часа нас посетили 11474 программиста и 1168 роботов. Сейчас ищут 302 программиста …


  1. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    переход в директорию через change directory (утилита cd):
    cd /path/to/dir

    «созданный репозиторий» на самом деле это просто каталог дот-гит в том каталоге где вызвана команда инициализации. следовательно rm -rf ./.git удалит «не там созданный репозиторий» не тронув прочие файлы.


  2. Catrina

    С нами с:
    24 апр 2015
    Сообщения:
    321
    Симпатии:
    0

    Работает. Спасибо :)

    Добавлено спустя 1 минуту 59 секунд:
    А как понять в каком каталоге сейчас находишься?


  3. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    print work directory — утилита pwd


  4. Catrina

    С нами с:
    24 апр 2015
    Сообщения:
    321
    Симпатии:
    0


  5. Catrina

    С нами с:
    24 апр 2015
    Сообщения:
    321
    Симпатии:
    0

    Не знала, что это так трудно. Вот что я делаю не так?

    1. acer-pc@acer MINGW64 ~/Desktop/GIT (master)
    2. $ git add /c/Users/acer-pc/Desktop/GIT/.git/test.php
    3. error: Invalid path ‘.git/test.php’
    4. error: unable to add .git/test.php to index
    5. fatal: adding files failed

    А если так, то вот:

    1. acer-pc@acer MINGW64 ~/Desktop/GIT (master)
    2. fatal: pathspec ‘test.php’ did not match any files

    Файл test.php точно существует и лежит в .git
    Скоро буду плакать. ))


  6. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    у тебя есть каталог /var/project
    в нем ты сделала инициализацию репы гита — появился каталог /var/project/.git — это всё и вся системы гит, но твои файлы ты не там располагаешь. продолжаешь работать с каталогом проекта.

    у тебя есть файл /var/project/file.php и он не добавлен в индекс. из корневого каталога проекта делаешь git add file.php — файл регистрируется в репе.
    то есть, нельзя находясь в / или в /home добавить файл /var/project/file.php в индекс так как ты находишься вне дерева за которым следит гит. только из рабочего каталога (или из его подкаталогов соответственно)

    и тебе не надо трогать дот-гит. вообще. там есть пара моментов типа настроек удаленных репозиториев и скриптов на разные события но тебе еще рано. поэтому наверное даже не заходи туда))) хотя там интересно прогуляться просто чтоб понять как работает гит.

    кстати не забудь настроить глобальное имя и адрес электропочты


  7. Catrina

    С нами с:
    24 апр 2015
    Сообщения:
    321
    Симпатии:
    0

    Ураа! Получилось! Благодарю! ))Это уже сделала в самом начале по учебнику. :)

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.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal package fontspec error the fontspec package requires either xetex or
  • Fatal not a git repository or any of the parent directories git как исправить
  • Fatal ni connect error 12560
  • Fatal ni connect error 12547
  • Fatal metro exodus ошибка как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии