Git commands I find useful

I'm no Git expert and I forget the commands easily. I'm not ashamed to admit I often reach for a GUI tool but I find myself using a handful of command-line snippets regularly.

I usually forget them so I thought I'd put them here:

  • git checkout <local-branch> - Check out an existing local branch.

  • git checkout -b <new-branch> - Create a new branch from the currently checked out branch and check it out.

  • git checkout -b <new-local-branch> origin/<remote-name> - Create a new local branch, check it out and pull changes from the remote branch.

  • git pull origin <remote-branch> - Get the latest changes from a remote branch.

  • git checkout tags/<tag-name> -b <new-branch-name> - Checkout a tagged branch and create a new branch from it. If a branch has been tagged (with a release number, for example) you can see the code at a particular point in history.

  • git branch --delete <local-branch> - Delete a local branch.

  • git push origin --delete <remote-branch> - Delete remote branch.

  • git reset --hard origin/<remote-branch> - If you want to get your local branch to match your remote branch. One example I've foolishly made is to get changes from a specific branch and accidentally overwrite a 'clean' local branch (e.g. develop). In my example I'd write this command git reset --hard origin/develop. An example scenario is highlighted here: https://graphite.dev/guides/git-hard-reset-remote.

Everyone has an opinion on the best commands to use. These are ones that have worked for me in the past and I'll continue to use these until I end up doing something catastrophic.