[fix] fatal: this operation must be run in a work tree in git


git - fatal this operation must be run in a work tree
% git add MyClass.java

fatal: this operation must be run in a work tree

If you are trying to stage a file or stage all files using git add -A and you get a fatal error saying this operation must be run in work tree, then its most likely that you are inside the .git hidden directory while trying to run the command,

% /myproj/.git/ master ls -la

total 40
drwxr-xr-x 7 root root 4096 Aug 16 08:52 .
drwxr-xr-x 3 root root 4096 Aug 16 08:41 ..
-rw-r--r-- 1 root root   23 Aug 16 08:41 HEAD
drwxr-xr-x 2 root root 4096 Aug 16 08:41 branches
-rw-r--r-- 1 root root   92 Aug 16 08:41 config
-rw-r--r-- 1 root root   73 Aug 16 08:41 description
drwxr-xr-x 2 root root 4096 Aug 16 08:41 hooks
drwxr-xr-x 2 root root 4096 Aug 16 08:41 info
drwxr-xr-x 4 root root 4096 Aug 16 08:41 objects
drwxr-xr-x 4 root root 4096 Aug 16 08:41 refs
Fix:

Make sure you are within your project directory and not inside .git or any sub-directories as shown in the above list when you run the add command,

% git add MyClass.java
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.