Git useful Commands

Basic Commands

  • git init: Initialize a new Git repository in your current directory.
  • git clone <repository>: Clone a repository from a remote source to your local machine.
  • git status: Show the current status of your working directory and staging area.
  • git add <file>: Add a file to the staging area.
  • git add .: Add all changes in the current directory to the staging area.
  • git commit -m "message": Commit changes in the staging area with a message.
  • git push <remote> <branch>: Push your committed changes to a remote repository.
  • git pull: Fetch changes from a remote repository and merge them into your current branch.

Branching and Merging

  • git branch: List all branches in your repository.
  • git branch <branch-name>: Create a new branch.
  • git checkout <branch-name>: Switch to a different branch.
  • git merge <branch-name>: Merge the specified branch into your current branch.
  • git branch -d <branch-name>: Delete a branch locally.

Viewing History and Logs

  • git log: View the commit history for the current branch.
  • git log --oneline: View a simplified version of the commit history.
  • git diff: Show changes between your working directory and the staging area.
  • git diff <branch1> <branch2>: Compare changes between two branches.

Working with Remotes

  • git remote -v: List all remote repositories associated with your local repository.
  • git remote add <name> <url>: Add a new remote repository.
  • git fetch <remote>: Fetch changes from a remote repository without merging them.
  • git push origin --delete <branch-name>: Delete a branch from the remote repository.

Stashing and Reverting

  • git stash: Temporarily save your changes without committing them.
  • git stash apply: Apply the stashed changes back to your working directory.
  • git revert <commit>: Create a new commit that undoes the changes from a specific commit.
  • git reset --hard <commit>: Reset your working directory and staging area to match a specific commit.

Tagging

  • git tag <tag-name>: Create a new tag for marking a specific commit.
  • git push origin <tag-name>: Push a tag to the remote repository.

Undoing Changes

  • git checkout -- <file>: Discard changes in a working directory file.
  • git reset HEAD <file>: Unstage a file without discarding changes.
  • git reset --soft <commit>: Reset to a previous commit but keep changes staged.
  • git reset --hard <commit>: Reset to a previous commit and discard all changes.