Git Commands

Note

This reference guide is meant to provide quick insights into commonly used Git commands. For a more detailed explanation, consider referring to the official Git documentation.

Basic Commands

Description

Command

Initialize a Repository

git init

Clone a Repository

git clone <repository_url>

Check Status

git status

Tip

Use git status often to see the state of your local repository.

Branching and Merging

Description

Command

Create a New Branch

git checkout -b <branch_name>

Switch to an Existing Branch

git checkout <branch_name>

Merge Branch

git merge <branch_name>

Delete a Local Branch

git branch -d <branch_name>

Delete a Remote Branch

git push --delete <remote_name> <branch_name>

Warning

Deleting a branch removes all of its associated commits that are not merged into another branch. Always double-check before deleting a branch.

Staging and Committing

Description

Command

Stage Files

git add <file_name>
git add .

Commit Changes

git commit -m "<commit_message>"

Amend Previous Commit

git commit --amend

Note

Using git commit --amend replaces the last commit with a new one. This can be dangerous if you’ve already pushed commits to a shared repository.

Remote Repositories

Description

Command

Add Remote

git remote add <remote_name> <remote_url>

Fetch Changes

git fetch <remote_name>

Pull Changes

git pull <remote_name> <branch_name>

Push Changes

git push <remote_name> <branch_name>

Tip

git pull is essentially a git fetch followed by a git merge. If you want to review changes before merging, use git fetch and then git merge.

History and Logs

Description

Command

View Log

git log

View Specific File History

git log -p <file_name>

Undo Last Commit

git revert HEAD

Note

git revert creates a new commit that undoes the changes from a previous commit. This is different from git reset, which discards commits.

Utility Commands

Description

Command

Stash Changes

git stash

Apply Stashed Changes

git stash apply

Clean Untracked Files

git clean -fd

Reset to a Specific Commit

git reset <commit_hash>

Warning

Be cautious when using git clean and git reset as these commands permanently delete your work.