Some useful Git commands

Suhail - Feb 27 - - Dev Community

Git is an essential tool in every developer's workflow. This article covers a few Git commands — some common, some not so much. Some of these commands are specific to GitHub, so make the necessary changes if you're using a different platform like GitLab.

I've also provided a wrapper script here that shortens the commands for ease of use. Download the script to ~/.local/bin. A few changes need to be made to the script, which will be mentioned below.

Clone repo

  • Using Git
git clone https://github.com/[user]/[repo] --branch [branch]
Enter fullscreen mode Exit fullscreen mode
  • Using script
git copy [user]/[repo] [branch]
Enter fullscreen mode Exit fullscreen mode

Clones the specified branch of the user's GitHub repo to your local machine. If you want to clone the default branch (usually main or master), the branch argument isn't necessary.

Set remote repo

  • Using Git
git remote set-url origin https://[token]@github.com/[user]/[repo]
Enter fullscreen mode Exit fullscreen mode
  • Using script
git sync [user]/[repo]
Enter fullscreen mode Exit fullscreen mode

Since "support for password authentication was removed" on GitHub, you'll need to use a token in order to commit. From GitHub, go to Settings -> Developer settings -> Personal access tokens -> Tokens (classic) to create a new token. From the dropdown, select Generate new token (classic), set the parameters, and hit Generate token.

Set the token to commit to the user's repo. If you're using the script, set the TOKEN variable within the script.

Undo last commit

  • Using Git
git reset --hard HEAD~1
git push origin HEAD --force
Enter fullscreen mode Exit fullscreen mode
  • Using script
git undo
Enter fullscreen mode Exit fullscreen mode

Revert to the state before the last commit. Requires you to be authorized to do so.

TL;DR

We've covered how to clone a repo, set a remote repo, and undo the last commit using Git commands as well as a wrapper script.

. . . .