Git Commands
Updated: January 30, 2023A list of useful Git commands for everyday use.
Stash
Stash is a way to save your work without committing it. It is useful when you want to change branches or pull the latest changes from a remote repository.
git stash push <file>
git stash
git stash list
git stash drop stash@{<number>}
git stash drop
git stash pop
git stash apply
git stash apply stash@{<number>}
Branch
It is useful when you want to work on a new feature and test it without affecting the main branch.
git branch
git checkout -b <name>
git checkout -
git branch -m <oldName> <newName>
git branch -d <name>
git push --set-upstream origin <name>
Stage and commit
Stage is a way to prepare your work for a commit. It allows you to commit your work in smaller parts.
git add .
git add <file>
git reset .
git commit -m "your commit message"
Overrides
Overrides are useful when you want to undo your work.
git commit --amend
git reset HEAD~
git reset --hard origin/<current-branch>
Restore previous work
Restore your work if you accidentally deleted it.
git checkout .
git checkout HEAD <file>
git reset --soft HEAD~1
Squash commits
First, check the number of commits you want to squash. Then, use that number to tell git how many commits to squash into one:
git rev-list HEAD --count
git rebase -i HEAD~<number-of-commits>
Rebase
Bring the changes from the "main" branch to the "staging" branch. Then, push the changes to the existing repository:
git checkout staging
git rebase main
git push
Sync feature branch with main branch
If you are in the "feature-branch" and need to pull in the latest changes from the remote main branch:
git checkout main
git pull
git checkout feature-branch
git pull --all
git merge main
Rename master branch to main in GitHub
First, make sure to change the name of the branch on GitHub:
https://github.com/:username/:repo-name/branches
Then, change the name of the branch locally:
git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a