Essential Git Commands
1. Basic Setup Commands
These help configure your Git environment:
git config --global user.name "Your Name"
git config --list # Verify the configuration
2. Working with Repositories
To initialize, clone, or create repositories:
git init # Initialize a new Git repository
git clone <repository_url> # Clone an existing repository
3. Adding and Committing Changes
Track files and commit them to your repo:
git status # Check the status of your working directory
git add <file> # Stage a file
git add . # Stage all changes
git commit -m "Your commit message" # Commit staged changes
4. Branching and Merging
Work on separate features or versions using branches:
git branch # List branches
git branch <branch_name> # Create a new branch
git checkout <branch_name> # Switch to another branch
git checkout -b <branch_name> # Create and switch to a new branch
git merge <branch_name> # Merge a branch into your current branch
5. Undoing Changes
Revert unwanted changes:
git reset --soft HEAD~1 # Undo the last commit (keep changes)
git reset --hard HEAD~1 # Undo the last commit (discard changes)
git checkout -- <file> # Discard changes in a specific file
6. Viewing History
Inspect the commit history:
git log # View commit history
git log --oneline # View concise commit history
git log --graph --oneline --all # View history with a graphical tree
7. Collaboration Commands
For pushing, pulling, and syncing with remote repositories:
git remote add origin <repository_url> # Add a remote repository
git push origin <branch_name> # Push changes to a remote branch
git pull origin <branch_name> # Pull updates from a remote branch
git fetch # Fetch updates without merging
8. Stashing Changes
Save changes temporarily:
git stash # Stash your changes
git stash apply # Reapply stashed changes
git stash list # View saved stashes
git stash drop # Delete a stash
9. Tags
For marking specific points in your repo:
git tag <tag_name> # Create a tag
git tag -a <tag_name> -m "Tag message" # Annotated tag with a message
git push origin <tag_name> # Push tags to a remote repository
10. Miscellaneous
Some advanced and handy commands:
git cherry-pick <commit_hash> # Apply a specific commit to another branch
git reflog # View the history of HEAD changes
git blame <file> # View line-by-line changes in a file
git diff # Show changes not yet staged or committed