Clean Local Working Branch

Sometimes if the local working branch messes up but you want to sync up with your remote branch, for example origin master, first remove all untracked files:

1
2
3
4
5
# -d: remove untracked dirs
# -f: force
git clean -df
# -x: remove ignored files as well
git clean -dfx

you can have a dry-run first to see what files will be removed

1
2
# -n: dry run
git clean -dfn

Check the commit logs in current branch:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# verbose
# -n: commit number
git log -n 10

# oneline and color
# color: show color
git log --oneline --color -n 10

# -p: show diff for each commit
git log -p --oneline --color -n 10

# show branch relationship
# --graph: show ascii graph
git log --graph --oneline --color -n 10

Then properly select one good commit that also appears in remote master branch, run

1
git reset --hard <good commit hash>

All the commits later than the good commit hash will be removed, then you can just run the command below to sync up remote master branch.

1
git pull origin master

Note that it’s safe to do git reset here because only I use this branch and I want to clean

Sometimes I see people use:

1
2
3
4
# reset to current commit, discard all uncommitted changes
git reset --hard HEAD
# HEAD~1: move to the commit right before HEAD
git reset --hard HEAD~1

HEAD points to your current commit, check by:

1
2
# get HEAD short hash
git rev-parse --short HEAD

so all that git reset --hard HEAD will do is to throw away any uncommitted changes you have and point to your latest commit.

0%