DEV Community

Cover image for All the Git Commands You Need to Know

All the Git Commands You Need to Know

Here is a collection of common scenarios of code management and the git commands needed for them:

1. Clone a repository to your local branch

git clone https://github.com/<organization>/<repository_name>.git
Enter fullscreen mode Exit fullscreen mode

2. Check if the current state of your local branch

git status
Enter fullscreen mode Exit fullscreen mode

3. Commit a change from your local to the remote repository

After doing edits (add/update/delete) to the files in your local repository, you can make them available to other developers by pushing your changes to the remote branch. First, stage the changes:

git add <path>
Enter fullscreen mode Exit fullscreen mode

Alternatives

  • git add --all
  • git add .
  • git add ../subpath

You can then add a commit message to your check-in. Some developer teams follow the Conventional Commit specification when adding commit messages, which dovetails SemVer and makes it easier to publish release notes based on widely known standards.

git commit -m "commit message"
Enter fullscreen mode Exit fullscreen mode

After adding a commit messsage, you can then push the change to a remote repository. If the remote_branch_name already exists in the remote repository, a simple git push command will do.

git push -u origin <remote_branch_name>
Enter fullscreen mode Exit fullscreen mode

4. Revert to a previous commit in the remote branch

There are times when you accidentally push a commit to an incorrect remote branch and wishes to revert to a previous commit. You can follow the following steps in order to do this.
First identify the commit id by checking the git history

git log
Enter fullscreen mode Exit fullscreen mode

You can then switch your local to an older commit_id

git reset --hard <commit_id>
Enter fullscreen mode Exit fullscreen mode

Then, force push the current state of the branch to the remote branch. Make sure that there are no restrictions in the remote branch against force pushes.

git push -f <remote_branch_name>
Enter fullscreen mode Exit fullscreen mode

5. Reset commit history in a git repository

These sequence of steps will essentially reset the git commit history of the remote repository by overwriting the main branch (which contains all commit history) with a fresh branch that contains all the files of the main branch:

git checkout --orphan temp-branch
git add -A
git commit -m "reset history"
git checkout main
git reset --hard temp-branch
git branch -D temp-branch
git push -f origin main
Enter fullscreen mode Exit fullscreen mode

And that's it! Let me know if you have questions in any of the use-cases!

Are there any other common scenarios in code management that is useful to you? Leave them at the comment section for others!

Top comments (0)