https://gbcdn.mrgcdn.ru/uploads/post/2934/image/original-25ae90aeb7d4039934160dbd7a5fd5a4.png
Периодически от студентов приходят вопросы о работе системы контроля версий Git. Частая причина возникновения этих вопросов — непонимание разницы между репозиторием и обычной папкой.
Чтобы исправить ситуацию, Ильнар Шафигуллин, эксперт по data science и методолог программы «Разработчик», подготовил небольшую заметку на эту тему. Давайте разберемся, как работать с папками и репозиториями с точки зрения практики, то есть без строгих определений.
Пункт 1. Про папки и репозитории
Если папка — это то, к чему мы все привыкли как пользователи компьютеров, то репозиторий — это что-то новое, что нужно создать, инициализировать. Сам по себе репозиторий без наших указаний не появляется. Репозиторий в наших задачах — это папка, над которой были произведены некоторые действия, и Git в ней начинает выполнять свои задачи, например:
-
отслеживать изменения файлов;
-
хранить информацию о ветках.
Важно! Репозиторий не возникает сам по себе, его нужно создать.
Пункт 2. Как понять, в репозитории мы находимся или в папке
Самый простой способ это сделать — набрать в терминале команду «git status». Если в ответ вы увидите ошибку «fatal: not a git repository (or any of the parent directories): .git», значит, в терминале вы вызываете команду не из репозитория, а из обычной папки. Если вы увидели что-то другое, то вы находитесь в репозитории или внутри одной из папок, которая находится в нем.
Важно! Репозиторий отслеживает изменения во всех вложенных в него папках.
Если вы сделаете репозиторием корневую папку на диске C (не делайте этого!), то весь ваш диск станет репозиторием и Git будет пытаться отслеживать все изменения на этом диске. Создаем репозитории очень аккуратно.
Пункт 3. Как можно создать репозиторий
На лекциях программы «Разработчик» мы рассматриваем два способа:
-
Если мы находимся в папке (!) и хотим сделать из нее репозиторий, то вызываем команду «git init», и эта папка становится репозиторием.
-
Если мы хотим клонировать репозиторий из GitHub на свой ПК, то мы пользуемся командой «git clone». При этом обратите внимание: не нужно пользоваться командой «git init», команда clone не только скачивает файлы из интернета, но и инициализирует репозиторий в скачанной папке. На самом деле она делает сильно больше, но нам важно, что в скачанной папке у нас уже будет репозиторий и никак дополнительно инициализировать его не надо.
Пункт 4. Внимательно следим за тем, из какой папки вы вызываете команды
Терминал всегда показывает, в какой папке вы сейчас находитесь, но первое время студенты чаще смотрят на то, какая папка открыта в визуальном интерфейсе VSCode, а не на то, что написано в терминале. Обращайте, пожалуйста, внимание на название папки, которая указана в приглашении к вводу команд терминала. До тех пор, пока вы не привыкнете к работе с терминалом, внимательно следите за тем, что вы создаете репозитории только во вновь созданных для урока папках. Не нужно создавать репозитории из рабочего стола или других больших папок.
Пункт 5. Не нужно создавать репозитории внутри другого репозитория
Повторюсь: не нужно создавать репозиторий внутри репозитория. Прежде чем вызывать команды «git init» или «git clone», сначала убедитесь, что вы точно не внутри репозитория. Вызовите «git status» и убедитесь, что вы находитесь в папке, а не в репозитории. Если «git status» выдал ошибку «fatal: not a git repository (or any of the parent directories): .git», значит, вы в этой папке можете воспользоваться одним из способов создания репозитория, рассмотренным выше и на лекциях. Либо «git init», либо «git clone», но не обоими одновременно.
Важно! Иногда студенты сначала вызывают «git init» и потом «git clone». Но тем самым вы нарушаете правило не создавать репозиторий внутри репозитория. Обращайте на это внимание.
Пункт 6. Как репозиторий сделать обычной папкой
Когда вы создаете репозиторий, у вас в папке появляется новая скрытая папка с названием «.git». Это специальная папка, в которой хранится все, что необходимо для работы системы контроля версий. Если вы удалите эту папку, то потеряете всю историю, которую Git успел сохранить, но при этом превратите ваш репозиторий обратно в папку.
Итак, чтобы из репозитория снова сделать папку, достаточно всего лишь удалить скрытую папку «.git». При этом вы потеряете историю, которую собрал Git (все коммиты, ветки и т. п.), но файлы в самой папке останутся в том же виде, в котором они были в момент удаления папки «.git».
Пункт 7. Что делать, если все вокруг стало репозиторием
У студентов, которые неаккуратно вводят команду «git init», такое встречается. Поэтому давайте разберемся, что делать в такой ситуации. Надо проверить, успели ли вы уже совершить такую ошибку. Создайте новую пустую папку, например на рабочем столе, и в терминале вызовите «git status» в этой папке. Если вы увидите «fatal: not a git repository …», то радуемся. Все у вас в порядке.
Если же вы увидели что-то другое, значит, ваша вновь созданная папка является частью какого-то другого репозитория. Важно: мы только что создали новую папку и внутри нее никаких команд кроме «git status» не вызывали, то есть мы не создали сейчас новый репозиторий, но Git при этом не говорит нам, что это «not a git repository». Это может быть только в том случае, если вы эту новую папку создали уже внутри другого репозитория, то есть чуть раньше сделали репозиторием ваш рабочий стол или даже весь ваш диск C. Вылечить такую ситуацию можно следующим образом: нужно найти репозиторий, который вы создали по ошибке, и сделать его обратно папкой (см. предыдущий пункт — нужно удалить папку .git).
Если вы работаете на Windows, включите отображение скрытых файлов и папок, так как папка .git скрытая. Далее начинаем подниматься по иерархии папок вверх и искать в них папки «.git». Например, если вы создали папку по адресу «C:UsersUserPicturesControlCenterScan», то сначала проверяете папку Scan, потом проверяете папку ControlCenter, потом Pictures и так далее, пока не найдете скрытую папку .git. Когда нашли и удалили, проводим проверку из начала этого пункта заново.
Успехов в освоении Git и терминала!
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.
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.
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.
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
Source: What are the differences between git file states
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.
Git these days is the most popularly used tool to manage your projects remotely while availing the benefits of version controlling. Sometimes while working with a particular git repository your operations just do not succeed and you face the fatal: not a git repository (or any of the parent directories):.git.
The error can be simply dealt if you follow the right steps to work with Git. In this article, we will go through the solutions that can help you in solving this “not a git repository” error.
What Causes the fatal: not a git repository Error?
Following are the possible reasons that can cause the error to be raised:
1. You tried to run the Git commands outside of a Git directory/ non-Git folder.
2. The repository in which you re trying to run the command has not been initialized in your project directory.
Solutions to Resolve fatal: not a git repository Error.
Solution#01: Initialize the Git Repository in your Project Folder.
If you are in your project folder, first check if this directory is initialized with git. Use the command ls -la to check this. If you are in git initialized folder you will see the .git/ folder in the output of the project.
If your project folder is not initialized as a git repository, you will not see the .git/ folder in it, like the output given below:
If this is the case, then first initialize the folder by using git init command in the project directory.
After running the git init command, you will now see .git/ folder in the project directory. Let’s check.
Solution#02: View and Open the Right Directory to Perform Git Operations.
To run Git commands successfully you need to be in the right project directory. Following are the steps to navigate to the right directory, make sure you follow them:
1. Open the Command Prompt and go to the right folder where you want to clone the repository, using the cd command.
2. Go to your existing Github repository that you want to connect with local project.
3. Copy the link to clone the repository.
4. Take this copied link and clone the repo with the git clone url. The output will somehow be like the following.
Now you are in the correct folder where your remote repository is cloned, and the git commands should be operational here if it is initialized correctly.
Conclusion
In this article we discussed about the possible causes that can give a rise to the fatal: not a git repository error. Later, we observed the possible solutions to deal with the error. It is indeed possible that if you are following the Git workflow properly you will not get a hit with such errors, but otherwise you can follow this guide to resolve the issue if it occurs.
A quick guide to fix git error fatal: not a git repository (or any of the parent directories): .git on windows, mac and heroku with simple steps.
1. Overview
In this tutorial, We’ll learn how to fix git error «fatal: not a git repository (or any of the parent directories): .git» on windows or mac os or Heroku.
Fixing this error can be done in 2 ways. But first, let us understand the error what is the meaning of the error.
This fatal error «not a git repository» is produced when you are running any git command on a non-git project location.
For example, run the git status command to see the current status of the git stage.
In the below example, I have created a new folder and executed the git status command.
MacBook-Pro-2:workspace $ git status fatal: not a git repository (or any of the parent directories): .git MacBook-Pro-2:workspace $
You can see the what is the reason for this error.
Not only git status command but also try with any commands like below. All will produce the same error «fatal: not a git repository (or any of the parent directories): .git» except «git init» and «git clone» commands.
$ git add *.java fatal: not a git repository (or any of the parent directories): .git $ $ git push fatal: not a git repository (or any of the parent directories): .git $ $ git commit -m 'git changes' fatal: not a git repository (or any of the parent directories): .git $ $ git remote -v fatal: not a git repository (or any of the parent directories): .git $ $ git branch fatal: not a git repository (or any of the parent directories): .git $
3. Fix 1 — fatal: not a git repository (or any of the parent directories): .git
This is the simple fix but you must have cloned the git repo already.
Then check the current location using pwd command and then run the ls -la command.
$ ls -larth total 0 drwxr-xr-x 27 venkateshn staff 864B Nov 29 19:19 .. drwxr-xr-x 3 venkateshn staff 96B Nov 29 19:22 . drwxr-xr-x 6 javaprogramto staff 192B Nov 29 19:22 Kotlin-Demo $ pwd /Users/javaprogramto/workspace/dummy $
From the above ls -larth command, we did not find any files related to the git like .git folder. That means this is not a git repositoiry. Becuase of thsi reason we are getting fatal not a git repository.
To fix now, we need to navigate to the right folder where we have cloned the git project.
ls command shown one folder Kotlin-demo. Let us run the unix ls command inside this folder and look for the git folders if any.
$ cd Kotlin-Demo/ $ $ ls -larth total 8 drwxr-xr-x 3 venkateshn staff 96B Nov 29 19:22 .. -rw-r--r-- 1 venkateshn staff 498B Nov 29 19:22 Kotlin-Demo.iml drwxr-xr-x 3 venkateshn staff 96B Nov 29 19:22 out drwxr-xr-x 6 venkateshn staff 192B Nov 29 19:22 . drwxr-xr-x 3 venkateshn staff 96B Nov 29 19:22 src drwxr-xr-x 13 venkateshn staff 416B Nov 29 19:22 .git $
Now, there is a one hidden folder with name «.git». This is indicagting that current folder is managed by git. So, if you run any git commands should not be thrown «is not a git repository» error now.
Let us see now, what would be output.
$ git branch * master $ $ git remote -v origin https://github.com/JavaProgramTo/Kotlin-Demo.git (fetch) origin https://github.com/JavaProgramTo/Kotlin-Demo.git (push) $
Great. It works well without any errors.
4. Fix 2 — fatal: not a git repository (or any of the parent directories): .git
In the previous section, we assumed this error encounterd after clonng the reposotory.
But now we did not clone any git repo.
In this case, we want to turn the current folder into git project but when we run git status command to see the files which are modified, we get the error fatal: not a git repository.
To fix in this case now, we need to initialize the current project into git using git init command.
$ mkdir newrepo $ ls -l total 0 drwxr-xr-x 6 venkateshn staff 192 Nov 29 19:22 Kotlin-Demo drwxr-xr-x 2 venkateshn staff 64 Nov 29 19:31 newrepo $ $ cd newrepo/ $ $ touch firstfile>txt $ ls -l total 0 -rw-r--r-- 1 venkateshn staff 0 Nov 29 19:31 firstfile>txt $ git status fatal: not a git repository (or any of the parent directories): >git $ $ git init Initialized empty Git repository in /Users/venkateshn/Documents/VenkY/blog/workspace/dummy/newrepo/>git/ $ git status On branch master No commits yet Untracked files: (use "git add <file>>>>" to include in what will be committed) firstfile>txt nothing added to commit but untracked files present (use "git add" to track) $
In the above commands,. first created a new folder with newrepo and went inside to run the command git status. But it thrown the error. Next, ran git init command. After that no issue with the git commands.
See the folder structure after git init. It has created the new hidden git folder with name «.git».
$ ls -lrtha total 0 drwxr-xr-x 4 venkateshn staff 128B Nov 29 19:31 .. -rw-r--r-- 1 venkateshn staff 0B Nov 29 19:31 firstfile.txt drwxr-xr-x 4 venkateshn staff 128B Nov 29 19:31 . drwxr-xr-x 10 venkateshn staff 320B Nov 29 19:31 .git
5. Conclusion
In this article, We’ve seen how to fix git error fatal: not a git repository (or any of the parent directories): .git in 2 ways.
Summary fix in 2 ways
5.1 Navigate to the correct git project location
5.2 If the current project is not a git project, please run git init command to make the project as git project.
In this post, we provide 4 fixes for a common error when you’re trying to create a Git repository.
If you’re using the Git program, there could be some instances where you’ll come across a number of errors, especially when creating a Git repository. One of these errors come in the form of this message:
fatal: not a git repository (or any of the parent directories): .git
If you’re fairly new to Git, then this might sound overwhelming for you. Fortunately, there are a few quick fixes you can follow to resolve this problem. We’ll try to tackle as many of them as possible to provide you with a working fix so you can get rid of such error.
The “fatal: not a git repository (or any of the parent directories): .git” error is a type of error which can come up each time you create a Git depository or try to add an existing repository to github.com. Some users reported encountering this error when entering a command and the website prompted them to put into the terminal.
There can also be instances where they’ll encounter the error when remote adding a Git repository into their local machine. In fact, there can be various causes for this error. That said, there are a few quick fixes for this.
How to Fix the “fatal: not a git repository (or any of the parent directories): .git” Error?
Resolving this specific git error can be a bit technical, but as long as you follow the steps, you’ll have a higher chance of fixing it.
1st Fix: Execute Git Init
The first fix we’re going to try is one which is provided by the Knowledge Base at Cloud Ingenium. This applies if you’re using a third-party website such as BitBucket for adding private Git repositories for free (considering that GitHub has some fees for doing so).
According to them, in order to add your repository to BitBucket, you’ll have to follow this instruction:
cd /path/to/my/repo
git remote add origin https://[email protected]/UserName/Project-Name.git
git push -u origin –all # pushes up the repo and its refs for the first time
git push -u origin –tags # pushes up any tags
Unfortunately, this resulted in the “fatal: not a git repository (or any of the parent directories): .git” error. Fortunately, this problem can be easily fixed. Here’s how:
- Start your local repository with a Git repository which is empty.
- After that, execute git init.
- Afterward, you’ll then receive this message: Initialized empty Git repository in /etc/somefolder/.git/
- Once you’re done, proceed to run a remote add origin command.
Video Guide: Copying a GitHub Repository to Your Local Computer
2nd Fix: Initialize Your Repository
This second fix is designed when you encounter the error message when pushing a repository to GitHub.com. Since the error will appear upon entering a command and the website prompts you to put the repository to the terminal, fixing the issue can be as simple as determining if you are in the right directory or not.
A user which goes by the name of jozefg at Stack Overflow recommends the following:
- Check if you’re in the right directory. You can do this by typing “ls” and checking whether it’s showing the right files or not.
- Initialize your repository. If you haven’t done it yet, simply type “git init”.
Hopefully, either one of the two can solve the fatal error message you’re encountering. If not, then proceed to the next fixes.
Video Guide: Git Tutorial For Creating Your First Repository
3rd Fix: Check the Directory or Initialize a Repository
This fix is made for individuals who are experiencing the same error when using the Heroku client package for Ruby on Rails programming. The error tends to happen when you open a new terminal and then enter this line:
git push heroku master
The issue, which was posted on Stack Overflow, comes with a few different fixes which can hopefully get rid of the error. Two of them, which are provided by users pjammer and Fiona T, involves the following:
- Making sure you’re on a git repository directory. To do this, simply type “pwd” then check if you’re in the right directory. It could be that you’re in the ~/ or another directory.
- Creating a git repository. To do so, simply use “git init” similar to that of the other fixes.
Video Guide: SignalR Tutorial 21 – Setting up a Git Repository
4th Fix: Setup Your Repository Properly
The 4th fix is from the same forum but is provided by another use by the name of Prakash Murthy. According to him, the error message could possibly be due to an improper git init setup. He recommends making sure that you’ve followed all the instructions with regards to the installation and setup of Git in your system. Here’s how:
- If it’s your first-time setup, you’ll have to do some one-time setups first. These include entering the following lines: $ git config –global user.name “Your Name” and $ git config –global user.email [email protected]. Keep in mind that the name and email address which you use will also be available in any public repositories you make.
- After that, the next step is to set up your repository. What you should do is to navigate to the root directory of your first app then execute the following lines:
$ git init
Initialized empty Git repository in
/home/ec2-user/environment/environment/hello_app/.git/
- Once you’re done, add your files to your repository using this line: $ git add –A. This line will add all files in your current directory except for those that have matched the patterns in the .gitignore file. This file will automatically be created with the Rails new command with regards to a Rails Project. However, you also have the option to add new patterns.
- Your files when then be stored in a staging area waiting for a confirmation. To check your files, you can use the $ git status command. If you want to commit the changes, simply use the “commit” command.
Hopefully, by properly setting up Git in your system, you’ll be able to get rid of the problem for good.
Forum Feedback
To understand more about the problem computer screen sideways, we read through different support boards. People were interested in knowing about how to fix a computer screen sideways, and computer screen sideways fix on Windows 10 and Windows 7. Some were also looking for answers on computer screen sideways Chromebook, HP, and Lenovo.
- A computer user complained that his screen got turned sideways while he was working on it.
- The person wasn’t computer savvy and was wondering how to fix the problem. He attempted to do it from Properties but didn’t have much success.
- Finally, he asked for help online, and another computer expert explained that he must have press some keys accidentally to change the position of the screen.
- To solve the problem, the person said that he had to press Ctrl + Alt + UP Arrow Key and that it should fix his screen.
- However, he warned that the solution might not work for Windows 10.
Another person also mentioned that he had a similar problem with his old Windows XP computer and that he looked for a solution online. People suggested that he tried the Ctrl + Alt + an arrow key until he found the correct screen position.
A computer expert explains that if you can’t turn your screen using Ctrl + Alt + Arrow Key, you can try the graphics option because the rotation of the screen is a feature of your graphics card.
- The user states that you if you use Windows 10, you should click on the empty desktop, choose Display Settings and select the right orientation from the Orientation drop-down menu.
- If you’re still using Windows 7 and Windows 8, you should choose Control Panel > Appearance and Personalization > Adjust screen resolution > Orientation.
- Another individual commented that if you couldn’t fix your sideway computer screen, you might try to restore the system to a previous point.
- However, he pointed out that it’s a last resort measure and the problem would rarely be so serious as to require a system restore.
A person observes that your screen might have turned sideways because you have a problem with your graphics card if you’re certain that you haven’t pressed anything.
- In such cases, he recommends that you update your graphics cards drivers.
- The update will take care of any missing or corrupted files and should resolve your screen troubles.
Another person pointed out that you can restore your screen by clicking on the desktop and choosing Graphics Options. - He also mentioned that if the Ctrl + Alt + UP command is not working your hotkeys might have been disabled.
A forum member complained that since he installed Windows 10, his screen started to turn sideways from time to time. He was able to fix it with the Ctrl + Alt + Arrow Key, however, it kept happening every time he would open a new application.
- The user went looking for a solution online, but he was unable to find one.
- The only thing that support suggested was to run the commands for corrupted files, which didn’t yield any result.
- He concluded that if the problem persisted, he would opt to uninstall Windows 10 and go back to Windows 8.1.
Another Windows 10 user also shared that he had to change the orientation of his screen several times after a major Windows update. The person was certain that he had saved his preferences to landscape orientation, but his device kept turning it back to portrait. Finally, he noticed in the settings that his device was set to tablet. After he turned it off, the problem disappeared.
Another person mentioned that he was experiencing the same Windows 10 problem and that the Ctrl + Alt + Arrow Key command wasn’t working for him. So, he reached out to support, and they suggested that he should roll back or uninstall the drivers of the display device. Support also said that he could try to update his graphics drivers from the official page of the manufacturer.
A user said that the screen on his Chromebook suddenly turned sideways. He was cleaning the keyboard, so he supposed that he had pressed the wrong buttons. Other forum members explained that he could rotate the screen by pressing Cntl+Shift+circular arrow, which would rotate the screen 90 degrees. The added that he should continue to press the buttons until the screen was back in its original position.
Conclusion
The “fatal: not a git repository (or any of the parent directories): .git” error is quite a technical error requiring a bit of technical and programming knowledge. However, if you already know how to work your way around Git, you should be able to resolve this issue using the above fixes.
Ryan is a computer enthusiast who has a knack for fixing difficult and technical software problems. Whether you’re having issues with Windows, Safari, Chrome or even an HP printer, Ryan helps out by figuring out easy solutions to common error codes.
An error that begins with “fatal” never sounds good. Do not worry; the cause of the fatal: not a git repository (or any of the parent directories): .git error is simple. This error is raised when you try to run a Git command outside of a Git repository.
In this guide, we talk about this error and why it is raised. We walk through two potential solutions so you can learn how to overcome a “not a git repository” error when working with Git. Without further ado, let’s begin!
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
fatal: not a git repository (or any of the parent directories): .git
The cause of this error message is running a Git command outside of a directory in which a Git folder is initialized. For instance, if you try to run “git commit” in a non-Git folder, you see an error. Git cannot run unless you view a folder configured with Git.
This is because Git is configured in a specific directory. Every Git project has a secret folder called .git/. You can view this folder by running the following command:
.git/ contains all of the configuration files for a repository. Without this folder, Git does not know anything about a project. This folder contains information such as the Git remotes associated with a repository, Git environment variables, and your current HEAD.
Run git commit
inside a folder that is not a Git repo:
This command returns:
fatal: not a git repository (or any of the parent directories): .git
Let’s solve this error.
Two Possible Causes
There are two possible causes for the “not a git repository” error.
Viewing the Wrong Directory
Check whether you view the correct directory. For instance, if you are in your home folder, you are not in a Git folder. If you are in a project folder, ensure it is the one where initialized a Git folder.
No Git Repository Has Been Initialized
If you are in a project folder and you see a “not a git repository” error, check whether a repository is initialized. You can do this by running ls -la
and checking for a .git/ folder.
If no .git/ folder is present, you have not initialized a repository. This means there is no record of Git inside a particular project folder.
To solve this error, run git init in your project folder:
The git init command initializes a new Git repository in your current working directory.
Conclusion
The “not a git repository” error is common. The cause is running a Git command in the wrong folder or running a Git command before initializing a Git repository.
Now you’re ready to solve the “not a git repository” error like an expert developer!