Can I use “git checkout –” on two files?

By | January 4, 2018
Questions:

Is it possible to use git checkout — on multiple files in order to discard the changes? If so how would I specify multiple files. Thanks.

Answers:

Run the command multiple times

git checkout -- path/to/file/one
git checkout -- path/to/file/two

Or specify the multiple files in the same line:

git checkout -- path/to/file/one path/to/file/two

You can also specify entire folders which will recurse to all files below them.

git checkout -- path/to/folder
git checkout -- . # for the current path

Questions:
Answers:

I accidentally modified all files in a directory by running find in my user’s git repo directory.

me@server:/home/me/gitrepo# git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   .bashrc
    modified:   dir/ec2-user.pem
    modified:   dir/readme.txt
    modified:   dir/root.pem
    modified:   dir/ec2-user.pem
    modified:   dir/readme.txt
    modified:   dir/root.pem
    modified:   dir/ec2-user.pem
    modified:   dir/ec2-user.pem.pub
    modified:   dir/readme.txt
    modified:   dir/root.pem

To correct my mistake I ran something like this command to find all modified files and checkout the files from master.

git status | grep modified | sed 's/^.*modified: //' | xargs git checkout

Questions:
Answers:

Use the following command

   git checkout path/to/fileName path/to/fileName2 path/to/fileName3

This will allow you to revert or discard your changes to the files fileName, fileName2 and fileName3

Note: that spaces in the path name will cause an issue with git. Use single quotes ” to encase the path name in such cases.

Leave a Reply

Your email address will not be published. Required fields are marked *