Git commits local changes which are not added - how can I stop this?

Viewed 46

I'm new to Git and use Git Bash locally. I have an issue when committing. As I learned, changes are only committed after they have been staged via add (unless you are using commit -a). But in contrast, I face the following scenario:

I add a file test.txt: git add test.txt

After that, I do some changes locally to this file without a further add. git status shows me - still as expected - changes to be committed and changes not staged for commit.

So far so good, but now it's getting irritating: I do a git commit -m "commit only staged changes" test.txt But as a result, my local changes are committed as well. Also, git statusnow only says "nothing to commit, working tree clean".

Can anybody explain to me, what needs to be done that only the staged changes are committed (what I actually understood as default behaviour...)? Thanks a lot in advance!

1 Answers

When you give a specific filename, as in

git commit [options] test.txt

then git will forego its default behavior and instead immediately commit all changes to that file. In this mode, it does not commit other changes that you have already staged.

If you want to commit only the staged changes, simply leave out the filename.

git commit [options]

Note that there is no way to commit only the staged changes to a single file while skipping both unstaged changes to that same file and staged changes to other files. You can either commit all staged changes (regardless of what files they are in), or you can commit all changes (staged or not) to one or more files. However, you can unstage changes to other files before committing, using git restore <filename> (if your version of Git is new enough to have it) or git reset <filename>.

Related