My top used git commands
git status
- this will tell you what branch you are on, if you have pending changes, pending commits, etc.
git log
- this will display a list of all the commits and their descriptions on the current branch
git fetch
- checks the remote repository for any changes, and “seeds” them, but does not apply them. This is a safe command to run anytime.
git pull
- pull commits from a remote repository and apply them to your local repository
git add
- takes your pending changes and gets them ready to commit. Typically you’ll just run:
git add .
and apply ALL of your pending changes, but sometimes you want to break apart your changes into separate commits. This is useful if having a stable git history is important.
git commit
- pretty straightforward git command, probably the most used command.
git push
- push your local commits to a remote repository
git checkout
git checkout -b BRANCH_NAME
creates a new branch and checks out the new branch while git branch BRANCH_NAME
creates a new branch but leaves you on the same branch.
In other words git checkout -b BRANCH_NAME
does the following for you.
git branch BRANCH_NAME # create a new branch
git switch BRANCH_NAME # then switch to the new branch
git reset
git reset --hard origin/branch_name
- This one I have ingrained in my head because of how useful it is. Anytime you maybe screw up your branch, or you want to just reset it to be exactly what is on a different branch, you can run this. The
origin/
part just means that you are referencing a “remote” branch, and “origin” is the name of your remote.
git rebase
- I generally use “rebase” instead of “merge” when I need to combine 2 branches. I do this to keep the git commit history clean. When you merge, it makes a new “merge commit” in the git history. When you rebase, it takes the commits from 1 branch and puts them on top of the commits from the other branch, without making a new commit.
git stash
- When you have pending changes that aren’t ready yet to commit, you can use stash. That way you “save” your pending changes and then you can switch branches and then read from the stash and then continue on with your changes.
git merge
- I usually don’t use git merge on the command line, but this is typically what would run when you merge a pull request.
Commit Messages
It’s super easy to write lazy messages. I still do it. But whenever I have to look back through commits and find that I did this, I hate myself. So do your best to write detailed commit messages. If you changed too many things, then try to break up your changes into commits that make sense.