Understanding Git Commands with Practical Examples
Git is a powerful version control system that helps developers manage changes in their codebase efficiently. Below, we break down the most commonly used Git commands with examples for better understanding.
1. git init
Description: Initializes a new Git repository in a directory.
Example:
mkdir my-project && cd my-project
git init
2. git add
Description: Stages changes for commit.
Example:
echo "Hello World" > file.txt
git add file.txt
3. git commit
Description: Saves changes to the local repository with a message.
Example:
git commit -m "Initial commit with file.txt"
4. git push
Description: Uploads local commits to a remote repository.
Example:
git push origin main
5. git pull
Description: Fetches the latest changes from the remote repository and merges them into the current branch.
Example:
git pull origin main
6. git branch
Description: Lists, creates, or deletes branches.
Example:
git branch feature-branch
git checkout feature-branch
7. git merge
Description: Combines changes from one branch into another.
Example:
git checkout main
git merge feature-branch
8. git rebase
Description: Moves or combines commits from one branch onto another.
Example:
git checkout feature-branch
git rebase main
9. git stash
Description: Temporarily saves uncommitted changes without committing them.
Example:
git stash
To retrieve stashed changes:
git stash pop
10. git blame
Description: Shows who last modified each line of a file.
Example:
git blame file.txt
11. git log
Description: Displays commit history.
Example:
git log --oneline
12. git reset
Description: Unstages or removes commits.
Example:
git reset HEAD~1 # Undo last commit but keep changes
13. git checkout
Description: Switches branches or restores files.
Example:
git checkout main
14. git diff
Description: Shows changes between commits, branches, or working directories.
Example:
git diff feature-branch main
15. git status
Description: Displays the state of the working directory and staging area.
Example:
git status
16. git switch
Description: Switches to a different branch.
Example:
git switch feature-branch
Final Thoughts
Understanding these Git commands will enhance your workflow and version control practices. Whether you’re working individually or collaborating in a team, mastering Git is essential for efficient project management.
