Published on

Useful GIT commands

Authors

Git

I'm creating this post for reminding myself about some useful git features... and updating it along the way.

-- Create new git local repository

git init

-- Normal way for committing and pushing

git add .

git commit -m "message"

git push origin master

-- Check status

git status

-- Create new branch

git checkout -b branchname

-- Switch between branches

git checkout branchname

-- Push branch to remote

git push origin branchname

-- Push local working branch to its correspondent on Github

git push origin HEAD

-- Merge branch into master

git checkout master

git merge branchname

-- How to remove file/dir from git after adding it to .gitignore

git rm --cached (file)

-- Command to check which files are ignored

git status --ignored

-- How to force revert to last status of master if pulled by mistake from remote depository

git reset --hard master@{time to revert back in minutes} possibly losing last commit

git reset --hard a0d3fe6 reverting to last commit

-- How to force revert after a rebase

git reflog check the HEAD{number} before the rebase starts git reset --hard HEAD{number}

-- Wrong name branch? No problem: delete the one in GH, rename the local one and repush it

git push origin :old-name-of-branch-on-github
git branch -m old-name-of-branch-on-github new-name-for-branch-you-want
git push origin new-name-for-branch-you-want

-- Need to change the branch but have uncommitted, unstaged changes that can conflict with the other branch? Stash comes to help

git stash list -- list all stashes

git stash -- stash (saves all unstaged changes in a temporary state under the current commit name)

git stash apply -- place back all the last stashed changes

git stash apply stash@{3} -- place back all the changes stashed at the stash n.4 (counting from 0)

git stash drop stash@{3} -- delete a particular stash

git stash clear -- delete all stashes

-- Make a diff between two branches. In a situation, for example, in which I need to rebase, or check the changes between the two branches

git diff branch1..branch2

-- Rebase. You have new merged changes on the master branch and need to merge in a clean way those changes in your local branch. It will place in the local log all master commit logs as well. After rebase, push -f origin HEAD

Flow:

  • git checkout master
  • git pull origin master
  • git checkout localbranch
  • git rebase master
  • git push -f origin localbranch

-- Get remote branch locally

git fetch

git checkout remote-branch

-- _...Or the alternative way

git checkout -b remote-branch

git pull origin remote-branch

-- _Delete multiple branches in git

git branch | grep "<pattern>" to preview the branches

git branch | grep "<pattern>" | xargs git branch -D to actually delete them