Fatal this operation must be run in a work tree как исправить

Just installed git on Windows. I set the GIT_DIR variable to be c:git and verified that this environment variable is maintained by cygwin (i.e. echo $GIT_DIR is what it should be). I went to the folder that I wanted to create the git repository for, let’s say c:www, and then ran:

git init
git add .

Then I get the error:

fatal: This operation must be run in a work tree

I’m not sure what went wrong, but the c:git directory has a config file that says:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = true
    symlinks = false
    ignorecase = true

I’m pretty sure this shouldn’t be bare and that’s our problem.

asked Sep 21, 2009 at 21:16

Bialecki's user avatar

1

Also, you are probably inside the .git subfolder, move up one folder to your project root.

answered Aug 3, 2012 at 18:34

blj's user avatar

bljblj

3,2242 gold badges15 silver badges6 bronze badges

1

The direct reason for the error is that yes, it’s impossible to use git-add with a bare repository. A bare repository, by definition, has no work tree. git-add takes files from the work tree and adds them to the index, in preparation for committing.

You may need to put a bit of thought into your setup here, though. GIT_DIR is the repository directory used for all git commands. Are you really trying to create a single repository for everything you track, maybe things all over your system? A git repository by nature tracks the contents of a single directory. You’ll need to set GIT_WORK_TREE to a path containing everything you want to track, and then you’ll need a .gitignore to block out everything you’re not interested in tracking.

Maybe you’re trying to create a repository which will track just c:www? Then you should put it in c:www (don’t set GIT_DIR). This is the normal usage of git, with the repository in the .git directory of the top-level directory of your «module».

Unless you have a really good reason, I’d recommend sticking with the way git likes to work. If you have several things to track, you probably want several repositories!

answered Sep 21, 2009 at 21:32

Cascabel's user avatar

CascabelCascabel

475k70 gold badges369 silver badges317 bronze badges

3

This should solve it:

git config --unset core.bare

EDIT: This happened because your repository is empty/new, thus bare. As you cal also see from your configuration, bare is set to true (default for empty/new repository). Your git-add command tries to add all files in an empty repository, which is not possible. So, error message is thrown. By setting this config value to false, you override this behavior.

answered Sep 4, 2018 at 7:29

Babajide M. Moibi's user avatar

1

Just in case what happened to me is happening to somebody else, I need to say this:
I was in my .git directory within my project when I was getting this error.
I searched and scoured for answers, but nothing worked.
All I had to do was get back to the right directory ( cd .. ).
It was kind of a face-palm moment for me.
In case there’s anyone else out there as silly as me, I hope you found this answer helpful.

fcm's user avatar

fcm

1,22715 silver badges28 bronze badges

answered Mar 11, 2014 at 0:11

Jacob Zimmerman's user avatar

2

Just clone the same project in another folder and copy the .git/ folder to your project.

Example

Create temp folder:

mkdir temp

switch to temp folder

cd temp/

clone the same project in the temp folder:

git clone [-b branchName] git@path_to_your_git_repository

copy .git folder to your projet:

cp -R .git/ path/to/your/project/

switch to your project and run git status

delete the temp folder if your are finished.

hope this will help someone

answered Apr 18, 2013 at 10:00

Festus Tamakloe's user avatar

Festus TamakloeFestus Tamakloe

11.2k9 gold badges52 silver badges65 bronze badges

2

I had this issue, because .git/config contained worktree = D:/git-repositories/OldName. I just changed it into worktree = D:/git-repositories/NewName

I discovered that, because I used git gui, which showed a more detailed error message:

git gui error

answered Mar 20, 2017 at 7:32

koppor's user avatar

kopporkoppor

18.8k15 gold badges118 silver badges158 bronze badges

3

Explicitly setting the GIT_DIR environment variable forces git to use the given directory as the git repository. It is never needed during normal use.

In your example, because have specified a GIT_DIR and it isn’t named .git (the leading dot is important) and you haven’t provided a --work-tree option or set the GIT_WORK_TREE environment variable, that you want a bare repository when you said git init.

Because a bare repository has no working tree a large selection of commands don’t make sense with a bare repository. git add is just one.

Is there a particular reason that you need to use a non-standard location for your git repository, rather than in a .git subfolder under the working tree root? While it’s possible to arrange this it tends to be more work and more liable to user mistakes.

answered Sep 21, 2009 at 21:41

CB Bailey's user avatar

CB BaileyCB Bailey

745k102 gold badges631 silver badges655 bronze badges

1

Create a bare GIT repository

A small rant: git is unable to create a normal bare repository by itself. Stupid git indeed.

To be precise, it is not possible to clone empty repositories. So an empty repository is a useless repository. Indeed, you normally create an empty repository and immediately fill it:

git init
git add .

However, git add is not possible when you create a bare repository:

git --bare init
git add .

gives an error «fatal: This operation must be run in a work tree».

You can’t check it out either:

Initialized empty Git repository in /home/user/myrepos/.git/
fatal: http://repository.example.org/projects/myrepos.git/info/refs not found: did you run git update-server-info on the server?

git --bare init
git update-server-info # this creates the info/refs file
chown -R <user>:<group> . # make sure others can update the repository

The solution is to create another repository elsewhere, add a file in that repository and, push it to the bare repository.

mkdir temp; cd temp
git init
touch .gitignore
git add .gitignore
git commit -m "Initial commit"
git push (url or path of bare repository) master
cd ..; rm -rf temp

hope this can help u

CB Bailey's user avatar

CB Bailey

745k102 gold badges631 silver badges655 bronze badges

answered Jul 9, 2012 at 7:58

user1329261's user avatar

2

In my case, I was in the same folder as «.git» file for my repo. I had to go one directory level up, it solved it.

answered May 17, 2018 at 18:37

chethan jain's user avatar

If nothing else seems to work, double-check the path in git config core.worktree. If that path doesn’t point to your working directory, you may need to update it.

The way I got this error was that I created a Git repository on a network drive. It worked fine on one computer but returned this error on another. It turned out that I had the drive mapped to a Windows drive letter on the computer where I created it, but not on the other computer, and Git saved the path to the work tree as the mapped path and not the UNC path.

answered Jun 11, 2019 at 15:45

Soren Bjornstad's user avatar

Soren BjornstadSoren Bjornstad

1,2321 gold badge14 silver badges24 bronze badges

Simple 2 liner solution:

1- Execute this command on your code repo:
git config —unset core.bare

2- Go to config file of your git repo and add this under core tag:

bare = false
worktree = /webroot/repo [Path to your root directory,one step above the git folder]

answered Jun 2, 2021 at 7:16

xikandar hayyat's user avatar

If an existing (non-bare) checkout begins giving this error, check your .git/config file; if core.bare is true, remove that config line

answered Aug 12, 2018 at 22:40

ThorSummoner's user avatar

ThorSummonerThorSummoner

16.4k15 gold badges134 silver badges145 bronze badges

The following command in my project directory fixed my issue

git --work-tree=/path/to/work/tree

To get your project path, enter the pwd command in your project directory if you are using Linux or MacOs

answered Mar 30, 2022 at 6:35

Ged Flod's user avatar

Ged FlodGed Flod

2,3892 gold badges15 silver badges40 bronze badges

If none of the above usual ways help you, look at the call trace underneath this error message ("fatal: This operation . . .") and locate the script and line which is raising the actual error. Once you locate that error() call, disable it and see if the operation you are trying completes even with some warnings/messages — ignore them for now. If so, finally after completing it might mention the part of the operation that was not completed successfully. Now, address this part separately as applicable.

Relating above logic to my case, I was getting this error message "fatal: This operation . . ." when I was trying to get the Android-x86 code with repo sync . . .. and the call trace showed raise GitError("cannot initialize work tree") as the error() call causing the above error message ("fatal: . . ."). So, after commenting that GitError() in .repo/repo/project.py, repo sync . . . continued and finally indicated error for three projects that were not properly synced. I just deleted their *.git folders from their relevant paths in the Android-x86 source tree locally and ran repo sync . . . again and tasted success!

answered Dec 11, 2015 at 10:41

geekie12's user avatar

Same issue i got, i did following steps,

  1. git init
  2. git add .
  3. git commit -m»inital setup»
  4. git push -f origin master

then it work starts working.

answered Jan 16, 2018 at 10:11

raghavendra's user avatar

Edited the config file and changed
bare = true
to
bare = false

answered Jan 7, 2019 at 22:41

Murt Moriarty's user avatar

In addition, apparently, this error will happen if you clone into NTFS Ram Drive.

answered Jul 28, 2020 at 10:04

Mendi Barel's user avatar

Mendi BarelMendi Barel

3,2901 gold badge23 silver badges24 bronze badges

In my case it was from github’s side
their servers were under maintenance or having an update
you can check the status of github services in this link:
https://www.githubstatus.com/

answered Mar 17, 2022 at 21:29

mahdi komaiha's user avatar

3

Разбираюсь с git.
2 машины одна c mac os другая вирутальная ubuntu 10.10
версии git там и там одинаковые

1.на mac os делаю репозиторий заливаю туда несколько файлов
2.c ubuntu делаю clone и меняю содержимое файлов
3.делаю push обратно на mac os — все пушится и работает как надо

но при попытке что то изменить на mac os в репозитарии получаю сообщение:
git fatal: «This operation must be run in a work tree
почему так происходит? как это поправить и что я сделал не так?


  • Вопрос задан

    более трёх лет назад

  • 12716 просмотров

Пригласить эксперта

в репе —bare нельзя работать, у нее нет рабочего дерева. Сделано так специально, чтобы нельзя было вносить изменения напрямую в общую репу на сервере

Вообще ошибка «git fatal: This operation must be run in a work tree» означает, что вы пытаетесь запустить команды git не из рабочей папки репозитория. Рабочая папка — это та папка, в которой находится папка .git (точка git) непосредственно с репозиторием.

Тоже столкнулся с этой проблемой. В рабочей папке эта же ошибка

Все делаешь как ниже описано?:

# Machine #1:
mkdir test1.git && cd test1.git
git init
echo "TEST" > README
git add README
git commit -m "Initial commit"

# Machine #2
git clone ssh://xxxxx/Users/username/test1.git
echo "Str2" >> README
git add README
git commit -m "Second commit"
git push origin master

# Machine #1
git pull origin master


  • Показать ещё
    Загружается…

28 мая 2023, в 00:03

8000 руб./за проект

27 мая 2023, в 23:03

10000 руб./за проект

27 мая 2023, в 22:55

1000 руб./за проект

Минуточку внимания

Git throws the fatal error that operation must be run in a work tree if you try to run a command outside the directory where git is absent. To understand this error, you need to first understand a work tree.

Git work tree is a linked copy of repository. So, when we clone a repo on our local system we create a work tree. Generally we call this the main working directory but it’s a work tree.

We can create multiple work trees for the same repository. They are used to keep different states of code so that we can complete some urgent work while we are working on major update in another work tree.

Reasons for getting error

1. If you are in .git folder and running some git command then you may get “operation must run in work tree” error.

2. If you are running git add command in an empty directory where there are no files to add.

3. GIT_WORK_TREE variable is not set for repository.

4. bare in config file is set to true.

Solution

1. Check if you are in .git folder. If you are then move to the parent folder using cd ..

2. Check if there are files in the directory before running git add . command.

3. Set bare in git config file to unset or false

git config --unset core.bare

4. Open .git/config file and check the value of worktree in it. If it is not correctly pointing to your project, then change it accordingly. You can use the below command to check the worktree value –

git config core.worktree

To set the worktree value, you can use this command –

git --work-tree=/path/to/work/tree

Conclusion

The solutions described in this article will resolve your issue of git fatal: Operation must run in working tree. If you still face problems after working on all the provided solutions, you can let me know through comments.

This is Akash Mittal, an overall computer scientist. He is in software development from more than 10 years and worked on technologies like ReactJS, React Native, Php, JS, Golang, Java, Android etc. Being a die hard animal lover is the only trait, he is proud of.

Related Tags
  • Error,
  • git,
  • git error,
  • git short

When working with Git, you might have encountered the error message fatal: this operation must be run in a work tree. This error message is usually displayed when trying to execute a Git command outside of a Git repository or when the repository is not properly initialized. In this guide, we’ll show you how to fix this error and ensure an efficient Git workflow.

Prerequisites

Before we begin, ensure that you have Git installed on your system and that you have basic knowledge of Git commands and workflows.

Solution

To fix the fatal: this operation must be run in a work tree error, follow these steps:

  1. Navigate to the root directory of your Git repository using the terminal or command prompt.
  2. Use the command git init to initialize the repository if it has not been initialized.
  3. Use the command git add . to add all files to the staging area.
  4. Use the command git commit -m "Initial commit" to commit the changes.
  5. Run your desired Git command again.

If the error persists, ensure that you are executing the Git command from the root directory of the repository.

FAQs

Q1. What causes the error message «fatal: this operation must be run in a work tree»?

This error message is usually displayed when trying to execute a Git command outside of a Git repository or when the repository is not properly initialized.

Q2. How do I initialize a Git repository?

You can initialize a Git repository by navigating to the root directory of your project in the terminal or command prompt and using the command git init.

Q3. What does the command «git add .» do?

The command git add . adds all files in the current directory and its subdirectories to the staging area.

Q4. What does the command «git commit -m» do?

The command git commit -m creates a commit with a message describing the changes made in the commit.

Q5. How do I know if a Git repository has been properly initialized?

You can check if a Git repository has been properly initialized by running the command ls -la in the root directory of the repository. If you see a .git directory, the repository has been initialized.

Conclusion

By following the steps outlined in this guide, you can fix the fatal: this operation must be run in a work tree error and ensure an efficient Git workflow. Remember to execute Git commands from the root directory of your Git repository and always ensure that the repository has been properly initialized.

  • Git Documentation
  • Git — The Simple Guide
  • Git Cheat Sheet

It is not possible to add Git init in bare repository as git add will take files from work tree and add them in an index. Now, bare repository will not have any work-tree that’s why will get an error like this.

Fatal: This operation must be run in a work tree

Now, what is the solution ? Create another repository elsewhere, add a file in that repository and, push it to the bare repository.

mkdir temp
cd temp
git init
touch .gitignore
git add .gitignore
git commit -m "Initial commit"
cd .. 
rm -rf temp

Now if you check git log, you will find initial commit

$git log

commit e5a3ee153c2a9eb8de3935fd97bcd9b66ce3971c
Author: Aagam Jain <aagam.jain@xyz.com>
Date:   Fri Aug 14 11:52:25 2015 +0530

Initial commit

and your repo will be on branch named “master”.

Hope this will be helpful !

I am tech lover and love to make something new everyday.
View all posts by Aagam Jain

Понравилась статья? Поделить с друзьями:
  • Как найти массу одного литра водорода
  • Как найти свой номер в вайбер
  • Как найти мой спам
  • Как составить таблицу диеты
  • Как найти свой телефон в украине