Advanced Git Commands
Let’s explore more powerful commands that help with advanced workflows and recovery operations.
📦 Temporarily Save Changes: git stash
Use when you want to switch branches but aren’t ready to commit changes.
git stash
Reapply stashed changes:
git stash apply
List stashes:
git stash list
Drop a stash:
git stash drop stash@{0}
🔍 Recover Lost Commits: git reflog
Shows a log of where HEAD
and branches have moved — useful for recovery!
git reflog
You can reset to a previous state using the hash:
git reset --hard <reflog_hash>
🧹 Clean Untracked Files: git clean
⚠️ Be careful! Deletes untracked files.
Dry run (see what will be deleted):
git clean -n
Actually delete:
git clean -f
📥 Fetch & Pull from Remote
Download new commits and branches without merging:
git fetch
Fetch + merge = pull:
git pull
Use
git pull --rebase
to rebase instead of merge.
🚀 Push to Remote Repository
Push current branch to origin
:
git push
Push to a specific branch:
git push origin branch-name
🏷️ Git Tags (Mark a Commit)
Tag a commit (e.g. for releases):
git tag v1.0
Push tags to remote:
git push origin --tags
List all tags:
git tag
🍒 Cherry-Pick Commits
Copy a single commit from one branch to another:
git cherry-pick <commit_hash>
Use this if you want to bring in one feature without merging the whole branch.
📂 Rename a File
git mv old_name.txt new_name.txt
Then commit:
git commit -m "Renamed file"
🔍 Blame for a Line of Code
See who last modified each line of a file:
git blame filename.py
🧪 Try It Yourself
Problem: Stash Changes and Switch Branches
Show Code
git stash
git checkout other-branch
# work here
git checkout main
git stash apply
Problem: Clean Untracked Files
Show Code
git clean -n # See what will be deleted
git clean -f # Actually delete