Git fatal this operation must be run in a work tree – Code Example

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

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.