Simply use:
git restore --staged <file>...
The aforementioned command will unstage the files staged for commit you have accidentally added via git add. However, this relies on you not having committed already. If you have committed but still want to undo the operation, see (in progress).
Example
You have added a couple of files to be staged for commit:
git add .
Following the best practices, you always check the status after such operations:
git status
At this point, you notice that a couple of unwanted files have been added into the list of files to be staged for commit:
On branch dev/VERS-5928
Your branch is up to date with 'origin/dev/VERS-5928'.
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitlab-ci.yml
new file: .gitmodules
modified: Makefile
modified: README.md
new file: project_foo/__pycache__/__init__.cpython-310.pyc
new file: project_foo/__pycache__/main.cpython-310.pyc
new file: project_foo/__pycache__/utils.cpython-310.pyc
In our example, you do not want push the last 3 files into the remote repository. The simplest solution is then to undo the git add operation so those files are no longer staged for commit:
git restore --staged project_foo/__pycache__/__init__.cpython-310.pyc
You can then repeat the operation for the last 2 remaining files.
However, even though this manual manoeuver is easily doable in our relative simple case, what about if in place of 3 files, way more files should be deleted?
In such case, the workaround to undo git add operations before commit for multiple files is as follow:
git restore --staged $(git diff --name-only --cached | grep "__pycache__")
Notes:
- To undo the git add operation after commit, see (in progress).
- To know more about the
git restorecommand (in progress). - The difference between
git reset,git restoreandgit rm(in progress).
