Получение «fatal: Not a git repository» при попытке удаленного добавления репозитория Git
Я представляю себя Git, следуя этому руководству:
- получение Jekyll работает на nearlyfreespeech.net
все работает нормально до той части, где РЕПО добавляется к моей локальной машине:
(после замены имени пользователя, NFSNSERVER и REPOAME с правильными именами) я получаю сообщение об ошибке:
можете ли вы помочь мне пройти этот шаг?
22 ответов
вы ввели локальный репозиторий Git, в который предполагается добавить этот пульт?
имеет ли ваш локальный каталог ?
попробовать git init .
вы получите эту ошибку, если вы попытаетесь использовать команду git, когда ваш текущий рабочий каталог не находится в репозитории Git. Это потому, что по умолчанию Git будет искать .git каталог (в корень проекта?), как указано мой ответ на «Git не будет показывать журнал, если я не нахожусь в каталоге проекта»:
по словам официальная документация ядра Linux git, GIT_DIR is [переменная окружения] set искать .git каталог (в текущем рабочий каталог?) по умолчанию:
если GIT_DIR переменная окружения устанавливается, затем она указывает путь для использования вместо .git для основания хранилище.
вам нужно cd в репозиторий / рабочую копию, или вы не инициализировали или не клонировали репозиторий в первую очередь, в этом случае вам нужно инициализировать РЕПО в каталоге где вы хотите разместить РЕПО:
или клонировать репозиторий
Примечание: это не отвечает на общую проблему, которая была проблемой OP, но к другой проблеме, где это сообщение об ошибке может возникнуть. Мне не хотелось делать новый вопрос, чтобы записать этот ответ, скажите мне, Должен ли я сделать это вместо этого 😛
Я попал в ситуацию, скорее всего, из-за какой-то коррупции определенного сбоя, который у меня был, что я получил эту ошибку, даже когда .git действительно существует.
так как у меня не было ничего, что действительно нуждалось в сохранении, я просто пошел с dummy way и сделал.
все еще не работает, хотя, например git log возвращает fatal: bad default revision ‘HEAD’ . Пульты были там хотя, так что я сделал git fetch —all и только потом git reset —hard origin/master заставить себя государство РЕПО был ранее.
обратите внимание, что если есть несохраненные изменения, вы можете увидеть их с git status , git diff и так далее. Тогда просто git diff yourfile > patch перед выполнением сброса.
по крайней мере для меня reflog ( git reflog ) исчезнуть полностью. Следовательно, если вы сделаете сброс, и были некоторые изменения, которые вы хотели предотвратить, я не уверен, что вы можете вернуть их после сброса. Поэтому убедитесь, что у вас есть все изменения, которые вы не можете потерять, в конечном счете, просто скопировав клон перед попыткой этого.
моя проблема заключалась в том, что для некоторых икот с моей ОС любая команда в моем локальном репозитории заканчивалась на «fatal: Not a git repository (или любой из родительских каталогов): .git», с включенной командой fsck.
проблема пустой головной файл.
я смог найти фактическое имя филиала, над которым я работал .git / refs / heads, а затем я сделал это:
в командной строке / CLI вы получите эту ошибку, если ваш текущий каталог не является репозиторием. Итак, вы должны сначала CD в репо.
эта проблема возникла у меня после того, как я переместил местоположение проекта git в файловой системе. Когда я запускал некоторые команды git, произошла ошибка, например:
Я нашел в /home/rospasta/path_old/gitprojecta/.travis/.git был записан абсолютный путь к старому местоположению проекта. Вручную обновление этого пути нового местоположения решило проблему для меня.
поэтому моя проблема может быть или не быть проблемой git, но HTH.
вероятно, слишком поздно, но другое решение, которое может помочь будущим посетителям. Сначала удалите старый !—4—>
затем снова инициализируйте git-РЕПО
похоже, что вы не собираетесь в свою конкретную папку. Например, если я работаю над проектом с именем bugsBunny и он сохраняется в папке d:/work:code , поэтому сначала вам нужно перейти в эту папку с помощью cd d:/work/code/bugsBunny , затем после этого вы можете продолжать использовать свои команды git.
просто введите следующее в cmd или git shell или любом другом терминале:
для этого вам нужно ввести одну команду, которая отсутствует в командах bitbucket
пожалуйста, попробуйте git init.
в моем случае я использовал Tortoise SVN и сделал ошибку, чтобы одновременно использовать функции Visual Studio GIT. Это заставило Visual Studio заблокировать головной файл внутри .папка git, чтобы ни VS, ни Tortoise не могли получить доступ к РЕПО, и я получил «фатальный: не РЕПО git. «ошибка обоих приложений.
устранение:
- зайти внутрь .git папку и переименовать » HEAD.блокировка «просто » голова»
- решите для одного приложения git admin и не трогай другую!—8—>
даже у меня была такая же проблема. я написал сценарий оболочки, который будет создавать резервные копии всех моих кодов в моем РЕПО git в рабочие дни недели в 17: 55 с помощью crontab. увидев журналы cron, я нашел вышеупомянутую проблему.
вышеуказанная проблема возникает только тогда, когда вы пытаетесь выполнить команды git из не-gir dir(т. е. из другого dir, который не является рабочей копией). чтобы исправить это добавить -C <git dir> в команде git вы выполняете такое, что git status будет git -C /dir/to/git status и git add -A будет git -C /dir/to/git -A .
в моем случае у меня была та же проблема, когда я пробовал любые команды git — (например, статус git) с помощью Windows cmd. так что я делаю после установки git для window https://windows.github.com/ в переменных среды добавьте путь класса git на» PATH » varaiable. обычно git будет установлен на C:/user/ «username» /appdata/local/git / bin добавьте это в путь в переменной окружения
и еще одна вещь на cmd перейдите в свой репозиторий git или cd, чтобы где ваш клон находится в вашем окне, обычно они будут храниться в документах под GitHub cd Document/Github / yourproject после этого вы можете иметь любые команды git
ниже ошибка кажется, что Gits не нашел .git-файл в текущем каталоге, поэтому бросает сообщение об ошибке.
поэтому перейдите в каталог в каталог репозитория, где у вас есть проверка кода из git, а затем запустите эту команду.
- $ git checkout
перейдите в исходную папку, где хранится локальное РЕПО, пример мой находится в c:/GitSource , щелкните правой кнопкой мыши в папке, нажмите Git bash здесь, затем git status.
для меня это было связано с искаженным владением в моем .git/ путь. root принадлежащего .git/HEAD и .git/index , предупреждения jenkins пользователь от запуска задания.
GIT_DIR должен быть unset: unset GIT_DIR
в моем случае я обнаружил, что git в windows стал чувствительным к регистру для буквы диска с некоторого момента.
после обновления двоичного файла git в командах cli windows, которые раньше работали, остановились. например, путь в скрипте был D:\bla\file.txt, в то время как команда git принято только d:\bla\file.txt
git работал нормально, и внезапно он начал показывать это fatal: Not a git repository (or any of the parent directories): .git сообщение.
для меня не уверен, что было повреждено .git Папка, я сделал git clone ** newfolder и скопировать все .папка git в мою поврежденную / старую папку, где я вносил изменения, прежде чем git начал показывать сообщение об ошибке..
все вернулось в норму, и git также распознал мои измененные / неустановленные файлы.
восстановить .git/ORIG_HEAD и другие корни .git repo файлы
Я получил эту ошибку после восстановления из резервной копии, видимо, файлы, содержащиеся в .git directory root не добрался до цели,но все подпапки сделали это сначала, я думал, что РЕПО было неповрежденным.
я исправил это, восстановив корневые файлы.
У меня была эта проблема с плагином Jenkins Git после проблем аутентификации с GitLab. Дженкинс докладывал о Хадсоне.подключаемый модуль.мерзавец.GitException: [. ]stderr: GitLab: проект, который вы искали, не найден. фатальная ошибка: не удалось прочитать из удаленного репозитория.’
однако, если я сделал «git clone» или «git fetch» непосредственно из окна Дженкинса (командной строки), он работал без проблем.
проблема была решена с помощью удаление весь /рабочая область каталог в папке Jenkins jobs для этого конкретного задания, например
предположительно, местные .папка git была устаревшей / поврежденной ?
в случае, если это помогает кому-то еще, я получил это сообщение об ошибке после случайного удаления .git / objects/
fatal: не репозиторий git (или любой из родительских каталогов): .git
Solving “fatal: not a git repository” (or any of the parent directories) Error

A Git repository is a collection of files and information regarding past changes made in them. While working with Git, you may encounter errors that seem confusing, especially if you are a beginner and the terms used are not familiar to you. In this article, we will explore what causes, how to prevent, and how to solve the fatal: not a git repository error.
Table of Contents:
- What is the “fatal: not a git repository” error?
- What causes “fatal: not a git repository”?
- Solving “fatal: not a git repository”
- Preventing “fatal: not a git repository”
- How do Git repositories work?
a. Stage the files
b. Commit the changes
c. Push the code - What are some common Git errors?
a. Permission Denied
b. Failed to Push Some Refs
c. fatal: A branch named <branch-name> already exists.
d. Can’t switch between branches - What causes Git errors?
- Conclusion
What is the “fatal: not a git repository” error?
Most of the Git commands must be executed against a Git repository. For example, if you run git push -u origin master outside of a git repository, Git will simply not know what to push and where to push. The error above, fatal: not a git repository (or any of the parent directories): .git , states that you tried to execute a repository-specific command, outside of the Git repository. Fortunately, even if it is a very common problem, it is also very easy to solve.
![]()
What causes “fatal: not a git repository”?
The fatal: not a git repository error makes it clear that you’re not in a git repository, but the reason you’re not in such a repository may be one of two:
1. You tried to run the command but did not navigate to the project folder where the git repository is located.
2. You are in the project directory, but you didn’t initialize the Git repository for that project folder.
Solving “fatal: not a git repository”
Let’s refer back to the previous section where we discussed the two situations in which one gets a fatal: not a git repository error. To solve the first situation, check the folder in which you are currently trying to run the command again.
Is that the correct folder? If not then simply use the cd command to navigate to the correct path.
There is a simple trick that you can use to be sure that you always open a command prompt in the correct folder. Navigate to the project directory using the file explorer and then type in the search bar, cmd. This will open a command prompt to the current folder path.
The trick for always opening a command prompt in the correct folder
For the second situation, you need to initialize the Git repository in your project folder. To do so, you need to navigate to the correct folder and then run the command git init , which will create a new empty Git repository or reinitialize an existing one.
Preventing “fatal: not a git repository”
When you run a Git command, the first step Git will take is to determine the repository you are in. To do this, it will go up in the file system path until it finds a folder called .git . Basically, the repository starts with the directory that has a .git folder as a direct child.
To prevent the fatal:not a git repository error, you need to make sure that you are in a Git repository before running any commands. One way you can do this is to check for the existence of the .git folder.
That period in front of the .git folder means that it’s a hidden folder. Therefore, it will not appear in the file explorer unless you have explicitly set it to show hidden folders.
On Windows, you can do this from the iew tab.

Enable hidden items in Windows from the View tab
If you are on Linux or you use a console emulator that allows you to execute Linux commands, you can run the ls command with the flag -a to lists all files including hidden ones.
![]()
Linux command to list all files
Another quick solution that you can use to check that you are inside a Git repository is to run the git status command. This command will show the current state of the repository if the current folder is part of a Git repository.
How do Git repositories work?
Git errors can be confusing, especially if you’re a beginner. This confusion mainly occurs because users are taught to create a connection between problem and solution, where someone encounters a problem and then looks for and uses a solution generally valid without trying to understand too much about the cause of the problem
This simple problem-solution connection is enough for most issues on Git: clone a repository, write some code, commit the changes and push the commits; or clone a repository, create a new branch, write some code, merge the branches and solve the conflicts. However, learning how Git works and its basic concepts will help you understand the technology you are working with and even do much more than those simple use cases described above.
Here’s some basic information to help you better understand how Git repositories work.

First and foremost, Git is a Distributed Version Control System (DVCS). With Git, we have a remote repository stored on a third-party server and a local repository stored in our local computer. Therefore, one can find the code in more than one place. Instead of having just one copy on a central server, we have a copy on each developer’s computer.
Source: Working with Git
Git, like any other software, must first be downloaded and installed in order to be used. You can even run the git —version command to see what your current version of Git is.
The first step to using a repository is to either clone one if you have access to it or to initialize one.
git clone <repo_path> and git init
These commands will create a new folder named .git, which will contain all the information about your repository that Git tracks: commits, branches, history, and so on.
The workflow of contributing to a Git repository is the following:
1. Stage the files
The first step is to add the files you want to add to a repository in the staging area. The purpose of this staging area is to keep track of all the files that are to be committed.
You can stage files using the git add <file_name> command or git add . to stage all the files.

Source: What are the differences between git file states
2. Commit the changes
The second step is to commit the changes. In this step, all the files that were added to the staged zone will be added to the local repository. The command for this is git commit -m «<your_message_here>» . The message should be something relevant about the changes you have added.
3. Push the code
The last step is to push your changes from your local repository to the remote repository with the help of the git push command.
What are some common Git errors?
Fatal: not a git repository (or any of the parent directories): .git is just one of many other errors that can occur when working with Git. Here is a list of other common errors that may occur along with a brief explanation.
1. Permission denied
Permission denied when accessing ‘url-path’ as user ‘username’
Git repositories can be of two types: public or private. In a public Git repository, everyone can view the code and clone it on their local machines. For the private ones, you need to be authenticated on the platform that the repository is hosted on in order to clone it onto your computer. At the same time, you need to have explicit rights to it.
The error stated above indicates that you possess an authenticated useraddname-password pair, but you do not maintain the files in the repository you are accessing. Thus, your assigned role in the repository must be increased to at least that of a maintainer or some similar position that the distribution platform provides, like maintainer, developer, admin, and so on.
2. Failed to Push Some Refs
git push rejected: error: failed to push some refs

The purpose of Git is to collaborate and share work within a project while all the participants contribute to the same code base. One common scenario is when someone else pushes some code to the same branch you are working on, and you are trying to make your changes as well. The above error indicates that there is one more commit that was pushed to the same branch, but you don’t have that commit on your local machine.
To fix this, you can easily run a git pull origin <your-branch> , solve the conflicts if any, and then run git push origin <your-branch> to push your changes as well.
3. fatal: A branch named <branch-name> already exists
Most VCS (version control systems) have some form of support for branching mechanisms, including Git. Branches can be created directly in the remote repository, or they can be created locally and then pushed to the remote repository.
To create a new branch locally, you can run either:
git branch <new-branch or git branch <new-branch> <base-branch>
The first one, git branch <new-branch> , is used to create a new branch based on the currently checked out (HEAD) branch, meaning that if you are on a branch master and run git branch dev , it will create a new branch named dev from the branch master .
The second one is used when you want to create a new branch from a different branch, then the one that you are currently checked out. git branch qa master will create a new branch named ‘ qa ‘ from the master branch.
The branch names must be unique, therefore the error above, fatal: A branch named <branch-name> already exists. , states that you already have a branch in your local repository with the same name.
4. Can’t switch between branches
Imagine this scenario: you have two branches, master and dev , both with committed files to the repository. On your local system, you do some changes in a file from the dev branch. At this point, if you want to move back to master and you run the command git checkout master , you will receive the following error:
error: Your local changes to the following files would be overwritten by checkout
This error means that you have some files that have been edited but not committed, and by checking out another branch, you’ll overwrite and lose these edits. The solution is to either commit these changes or if you don’t want to commit them yet, to stash them.
What causes Git errors?
Git errors are like any other CLI software errors. Most of the time, they represent a misuse of the command, wrong command names, missing parameters, wrong scope, etc.
There may also be cases where the error is not a user error but a software error. In those situations, either the application encountered a bug or the integrity of the application is corrupted. This can usually originate from missing data or the unintentional deletion of the required files.
In the former case, you can report the bug, and once it is fixed, the Git application can be updated. For the latter, the easiest solution is to remove the software and install it again.
Conclusion
Git is one of those applications you can use without ever thoroughly learning it because most of the time, the way you use it is straightforward as you limit yourself to the same commands over and over again. But if you never take the time to understand how it works and the philosophy behind it entirely, the confusion will never go away, and you can reach a stalemate if you have to do a few more complex operations. In this article, we covered the «fatal:not a git repository» error and everything to do with it, and then explored a few more Git errors.
It’s not complicated. Use Komodor and start troubleshooting intelligently.
"fatal: Not a git repository (or any of the parent directories)" from git status
This command works to get the files and compile them:
However, git status (or any other git command) then gives the above fatal: Not a git repository (or any of the parent directories) error.
What am I doing wrong?
![]()
13 Answers 13
You have to actually cd into the directory first:
I just got this message and there is a very simple answer before trying the others. At the parent directory, type git init
This will initialize the directory for git. Then git add and git commit should work.
In my case, was an environment variable GIT_DIR , which I added to access faster.
This also broke all my local repos in SourceTree 🙁
Sometimes its because of ssh. So you can use this:
![]()
in my case, i had the same problem while i try any git — commands (eg git status) using windows cmd. so what i do is after installing git for window https://windows.github.com/ in the environmental variables, add the class path of the git on the «PATH» varaiable. usually the git will installed on C:/user/»username»/appdata/local/git/bin add this on the PATH in the environmental variable
and one more thing on the cmd go to your git repository or cd to where your clone are on your window usually they will be stored on the documents under github
after that you can have any git commands
you have to «cd projone»
then you can check status.
One reason why this was difficult to notice at first, i because you created a folder with the same name already in your computer and that was where you cloned the project into, so you have to change directory again