I mistakenly added files to Git using the command:
git add myfile.txt
I have not yet run git commit
. Is there a way to undo this, so these files won't be included in the commit?
If you have committed changes to a file (i.e. you have run both git add and git commit ), and want to undo those changes, then you can use git reset HEAD~ to undo your commit.
The easiest way to undo the last Git commit is to execute the “git reset” command with the “–soft” option that will preserve changes done to your files. You have to specify the commit to undo which is “HEAD~1” in this case. The last commit will be removed from your Git history.
To unstage commits on Git, use the “git reset” command with the “–soft” option and specify the commit hash. Alternatively, if you want to unstage your last commit, you can the “HEAD” notation in order to revert it easily. Using the “–soft” argument, changes are kept in your working directory and index.
You can undo git add
before commit with
git reset <file>
which will remove it from the current index (the "about to be committed" list) without changing anything else.
You can use
git reset
without any file name to unstage all due changes. This can come in handy when there are too many files to be listed one by one in a reasonable amount of time.
In old versions of Git, the above commands are equivalent to git reset HEAD <file>
and git reset HEAD
respectively, and will fail if HEAD
is undefined (because you haven't yet made any commits in your repository) or ambiguous (because you created a branch called HEAD
, which is a stupid thing that you shouldn't do). This was changed in Git 1.8.2, though, so in modern versions of Git you can use the commands above even prior to making your first commit:
"git reset" (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).
Documentation: git reset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With