Skip to main content

Git commands that we all need to remember

Member for

2 years 7 months
Submitted by admin on

Git is fantastic and is used by companies all over the world it's used on every major platform and has revolutionised the way we manage code for last few decades.

But there are times when you need to find that odd command because something has broken. 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 to 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 user commits in the logs

~$ git log --author="username"

I want see what was committed

~$ git log -p 
~$ git log -p -

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

~$ git rm --cached  

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 
new mode 

// Fix
~$ git config core.filemode false

Force pull all files from the 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

Search log history by date range

git log [--since=<date_from>] [--until=<date_to>]