Git

Useful Git Commands

Repositories

Create a New Repo

git init
git add -A
git commit -m "first commit"
git branch -M main
git remote add origin <REPO_LINK>
git push -u origin main

Push an Existing Repo

git remote add origin <REPO_LINK>
git branch -M main
git push -u origin main

Branches

Create a Branch

The branch will be created locally, meaning that it will not be visible on GitHub.com until it's pushed.

Switch a Branch

Cannot switch to another branch if uncommitted changes exist on the current branch.

Push to Branch

Delete a Branch

Rename a Local Branch

Unstage All Changes on Local Branch

Unstage a File on Local Branch

Divergent Branches

Sometimes, when attempting to pull changes on a branch, an error occurs with the following information:

The following command is the preferred way to ensure a clean, linear history. It will fetch the changes from the remote branch, and instead of merging the fetched changes into the local branch, it applies the local changes on top of the changes retrieved.

Merge Main to Local Branch

When working on a local branch and new updates have been pushed to the main branch by someone else, it may make sense to get those changes reflected on your local branch. To do that, run the following commands:

Commits

Revert to Previous Commit

Revert all Unstaged Changes

The following command will revert all unstaged changes on the current branch. For example, any changes seen when running git status before staging will be reverted when running the command below.

Amend Last Commit

The following is useful in the scenerio where you need to make more changes right after pushing to GitHub, but don't want to create another commit. This is a way to add new changes to the last commit without editing the commit message.

Restore File to a Specific Commit

Accounts

Display Username and Email in Current Repo

Change Username and Email in Current Repo

This overwrites the global config username and email.

Change Username and Email Globally

This will be default config used if username and email are not set in a repo.

Last updated