Commonly Used Git Commands

Git is the most widely used Version Control System. Here are most common git commands:

Initial git setup:

Initialize git repository:
 git init
Add all files:
 git add .
   (undo: git reset <file>)
Commit changes:
 git commit -m "<message>"
Add all files (except new files) and commit with a single command:
 git commit -am "<message>"
View commit history:
  git log
View state of the working directory and the staging area:
 git status
- Undo commit:
 git reset HEAD~1 (last commit)
 git reset --hard <commit_message> (any previous commit) Note:--soft keeps in filesystem but --hard removes from local filesystem as well.

Sync With Remote:

Add a remote Repository:
 git remote add <name> <repo_url>
View Remotes:
 git remote -v
View remote URL:
  git remote get-url origin
Update Remote:
 git remote set-url origin <url>
Delete Remote:
 git remote remove origin
Pull changes from remote repo:
  git pull <remote> <branch name> e.g. git pull origin master
Push a branch to remote repo:
  git push <remote> <branch name> e.ggit push origin master
Push local branch to remote and setup tracking (upstream):
  git push -u <remote> <branch>

Remove tracking:

Remove 'file' from git repository:
  git rm --cached -r file (-r for directory)
Remove 'file(s)' from previous commits:
git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch <file-path>' -f HEAD

*If you have already initialized the remote repo with readme and try to pull from remote to local, you may encounter error: refusing to merge unrelated histories
solutiongit pull origin master --allow-unrelated-histories

Branch Commands:

Show all branches(local and remote):
 git branch -a
Create new branch:
 git branch <branch_name>
Switch between branches:
 git checkout <branch_name>
Create a local branch with same name as remote branch:
 git checkout -t <remote>/<branch>
Create another local branch from existing local branch:
 git checkout -b <new_branch> <old_branch>
Discard all changes:
  git checkout .
Delete branch:
 git push --delete <remote> <branch>
 git branch -b <local_branch>

Stash Command:

Save changes temporarily and reapply them before next commit:
 git stash
 git stash list
 git stash apply

Rebase Command:

To combine all local commits and merge to single commit:
 git rebase -i HEAD~4

Use Gitignore:

Note: First add .gitignore file and commit.

To untrack tracked files/dir:
 git rm --cached -r(for dir)














Comments