Dec 30, 2024
Git Commands: A Quick Guide
Git is a powerful version control system used for tracking changes in code. This guide provides a concise overview of key Git commands for initializing repositories, tracking changes, and managing versions.
1. Initialize a Repository
Create an empty repository in a new directory:
git init repo_nameCreate a repository in the current working directory (cwd):
git init
2. Check Repository Status
View untracked files and pending commits:
git status
3. Stage Files for Commit
Add all files and folders to staging:
git add .Add a specific file to staging:
git add filename.txt
4. Commit Changes
Commit with a message:
git commit -m "Commit message here"
5. View Commit History
List all commits in reverse order:
git logLimit the number of commits displayed:
git log -4Filter by file:
git log filename.txtFilter by date range:
git log --since='2024-04-02' --until='2024-05-03'
6. Show Specific Commit Details
Display details of a specific commit:
git show commit_hash
7. Compare Changes
Compare a file with its last committed version:
git diff filename.txtCompare staged changes:
git diff --staged filename.txtCompare two commits:
git diff commit1 commit2Compare the last commit with the previous one:
git diff HEAD~1 HEAD
8. Revert Changes
Revert to the latest commit:
git revert HEADRevert to the previous commit:
git revert HEAD~1Skip opening the editor for a message:
git revert HEAD --no-edit
9. Restore Files
Restore a specific file to a previous version:
git checkout HEAD~1 -- filename.txtUnstage a file:
git restore --staged filename.txtUnstage all files:
git restore --staged .
Conclusion
By mastering these essential Git commands, developers can efficiently manage their codebase, track changes, and collaborate effectively.