git checkout, clean, vs reset


Do you know the difference between git checkout, git clean, and git reset?

We’ll compare them using the following example below.

Example

Given the following index and working tree:

$ git status
On branch 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:   modified.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        untracked.txt

no changes added to commit (use "git add" and/or "git commit -a")

Or in the short format:

$ git status -s
 M modified.txt
?? untracked.txt

git checkout

Changes to modified files are discarded but untracked files are untouched:

$ git checkout .
$ git status -s
?? untracked.txt

See docs on git checkout for more info.

git clean

Untracked files are removed but modified files are unchanged:

$ git clean -f
Removing untracked.txt
$ git status -s
 M modified.txt

To remove untracked directories in addition to untracked files, run git clean -f -d.

See docs on git clean for more info.

git reset

Changes to modified files are discarded but untracked files are untouched:

$ git reset --hard
HEAD is now at sha1234 my commit message
$ git status -s
?? untracked.txt

Thus, to discard modified files and remove untracked files:

$ git reset --hard && git clean -f -d

See docs git reset for more info.



If you enjoyed this post, please consider supporting this site!