1. Initialize a New Git Repository
Use this command to create a new Git repository in your current project directory:
git int
To clone an existing remote repository:
git clone repository_url
2. Making Changes and Saving Work
Check the status of your working directory:
git status
Add specific files to the staging area:
git add filename
Add all modified files:
git add
Commit the staged changes with a message:
git commit -m "Your commit message"
3. Parallel Development with Branches
Keeps the commit history of both branches.
Create a new branch:
git commit -m "Your commit message"
git branch
Switch to that branch:
Create and switch to a new branch in one command:
git checkout branch_name
List all branches:
git branch
4. Syncing with Remote Repositories
Pull changes from the remote repository (fetch + merge):
git pull"
Push your local changes to the remote branch:
git push origin branch_name
5. Viewing Commit History (Logs)
To see commit history with messages:
git log
Condensed view (one line per commit):
git log --oneline
6. Save Work Without Committing (Stashing)
If you're not ready to commit but want to save your changes temporarily:
git stash
View stashed items:
git stash list
Apply the latest stash:
git stash apply
Apply and remove from stash list:
git stash pop
7. Retrieve a Specific File or Directory
To restore a file from a previous commit:
git checkout commit_hash -- filename
To retrieve a full directory:
git checkout commit_hash -- directory_name/
8. Retrieve a Specific Commit
To view a specific commit:
>git show
To revert your repository to a specific commit (soft, mixed, or hard):
>git reset --soft commit_hash# Keeps changes staged commit_hash -- directory_name/
>git reset --mixed commit_hash# Keeps changes but unstaged
>git reset --hard commit_hash # Discards all changes
9. Merging Branches: Git Merge vs Git Rebase
When a feature branch is ready to be merged into main or master, you have two
options:
Option 1: Git Merge
To restore a file from a previous commit: # Discards all changes
git checkout
To retrieve a full directory:
To restore a file from a previous commit: # Discards all changes
git checkout commit_hash -- directory_name/
Option 2: Git Rebase
Rewrites the commit history to make it linear:
git checkout feature_branch # Discards all changes
git rebase main # Discards all changes
Then merge back into main:
git checkout main
git merge feature_branch # Discards all changes
Note: Use rebase when you want a clean history; use merge when preserving history is
more important.