Git commands that we all need to remember

You are here

Git is fantastic but there are times when you need to find that odd command because you have stuffed something up. Here are some I use on those occasions, firstly open the terminal and navigate to the root directory of the Git repo.

You didn't want to commit that

~$ git reset --soft HEAD~1

I want to remove the second last commit

~$ git rebase -i HEAD~2

The master branch commits have moved ahead from my-current-branch when I first branched off

~$ git checkout my-current-branch
~$ git rebase master

I need to see the changes before I commit

~$ git diff [filename]

I need to see a users commits in the logs

~$ git log --author="username"

I want see what was committed

~$ git log -p <commit name>
~$ git log -p -<number be commits of seen>

Removing a file from git repo so it can be added to .gitignore

~$ git rm --cached  <path/filename>

git config --global credential.helper cache allows you login to a git account for a period of time this will default to fifteen minutes

~$  git config --global credential.helper cache

To change the default password cache time out use the command below. 3600 is one hour

~$ git config --global credential.helper 'cache --timeout=3600'

Ignore old mode new mode

// Issue
old mode <foo>
new mode <foo>

// Fix
~$ git config core.filemode false

Force pull all files from origin

~$ git fetch --all
~$ git reset --hard origin/master
~$ git pull origin master
~$  git rm -r --cached .
~$ git add .
~$  git commit -am 'git cache cleared'
~$  git push

Option 2 remove files remembered by git but it is really dangerous

~$  git filter-branch --index-filter 'git rm --cached --ignore-unmatch filename' HEAD

Clean Step - beware: this will delete files:

  • To remove files, run git clean -n
  • To delete files, run git clean -f
  • To remove directories, run git clean -f -d or git clean -fd
  • To remove ignored files, run git clean -f -X or git clean -fX
  • To remove ignored and non-ignored files, run git clean -f -x or git clean -fx



Stash one file before commit

~$ git add .
~$ git reset the_file_to_stash
~$ git stash save --keep-index

Applying a patch

~$ patch -p1 < 0001-filename.patch