2

I think that's most common question about git. But I have specific problem.

For example I got few files in my local git and have modified some of them. Once I've recalled that I made a mistake in a file, but I want to save the changes in the rest files. I can change their status to staged by git add, but how to commit only chosen files and return original version of file that I don't want to commit right now.

So, I guess, my question is how to return unmodified version of a file with saving changes of another files. Thank you

DisplayName
  • 211
  • 2
  • 16
  • 1
    Possible duplicate of [How do I commit only some files?](https://stackoverflow.com/questions/7239333/how-do-i-commit-only-some-files) – jaroslawj Sep 26 '19 at 21:23
  • Oh see, imagine, that I have 3 modified files: file1 file2 and file3. I don't want that file3 will be committed, I want it to be as most recent version. But I want use changes of file1 and file2, they satisfy me. So, I want they'll be staged and committed, but at the same time I want return state of file3 to unmodified original version – DisplayName Sep 27 '19 at 03:27

3 Answers3

2

You can use the new command git restore (less confusing than git checkout), with Git 2.23+ (August 2019)

You can restore both the index and the working tree (this the same as using git-checkout)

$ git restore --source=HEAD --staged --worktree hello.c

or the short form which is more practical but less readable:

$ git restore -s@ -SW hello.c
Community
  • 1
  • 1
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
1

Based on your comment, if you have three files: file1, file2, file3 and you want to only commit file1, file2 and want the unmodified version of file3, you can use the below checkout command at file level.

git checkout master -- file3 # then copy the version of file3 
                                  # from branch "master"

This way, the file3 is copied from master branch to your local.

Now, you can go ahead and commit.

git add file1, file2 
git commit -m "modified file1, file2"
Venkataraman R
  • 8,468
  • 1
  • 21
  • 39
1

I think you may also use the command line :

git add -p

This allows you to review all your uncommited files, one by one and choose if you want to commit them or not.

Then you have some options that will come up for each modification: I use the "y" for "yes I want to add this file" and the "n" for "no, I will commit this one later".

Stage this hunk [y,n,q,a,d,K,g,/,e,?]?

As for the other options which are ( q,a,d,K,g,/,e,? ), I'm not sure what they do, but I guess the "?" might help you out if you need to go deeper into details.

The great thing about this is that you can then push your work, and create a new branch after and all the uncommited work will follow you on that new branch. Very useful if you have coded many different things and that you actually want to reorganise your work on github before pushing it.