I deleted the wrong file before my coffee kicked in. Again. ☕ Happy Git Friday! I can't even count the number of times this has happened. Early morning. Terminal open. Brain not fully online yet. I'm cleaning up a working directory, trimming files, moving things around. And then I realize I just deleted something I needed. Not git rm. Just rm. Gone from the filesystem. No recycle bin. No undo. Just a blank stare at the terminal and the slow realization that the file I need for today's work is gone. The first time it happened, I panicked. I started thinking about backup systems, recovery tools, whether I could rewrite it from memory. Then someone said: "It's in a git repo. Just check it out." git checkout -- filename The file came back. Exactly as it was the last time I staged it. Git had a copy in the index the entire time. I just didn't know how to ask for it. That one command has saved me more times than I'm willing to admit. All of them before the first cup of coffee. The Danger Zone (When Deletions Feel Permanent): 🔹 rm deletes from the filesystem. Git doesn't know or care. But if the file was tracked and staged, the last staged version is still in the index. You can recover it. 🔹 git add on a deleted file stages the deletion. If you accidentally delete a file and then run git add ., you've told git you meant to delete it. Now recovery requires checking out from a commit, not just the index. 🔹 git rm is intentional. It removes the file AND stages the removal. That's a deliberate action. An accidental rm followed by git checkout -- is the recovery path for unintentional deletions. ❓ Question of the Day: You deleted a file in the working directory and want to recover it from the index. Which command do you use? Ⓐ git checkout -- filename Ⓑ git add filename Ⓒ git rm filename Ⓓ git recover filename 👇 Answer and breakdown in the comments! #Git #GitOps #DevOps #DamnitRay #QOTD
Git Recovery: Don't Panic, Use git checkout -- filename
More Relevant Posts
-
My git config grew over years. After a recent round of improvements I decided to write about it :) Five settings that made the biggest difference: rerere.enabled = true — Git records how you resolved a conflict. Same conflict again? Applied automatically. The sleeper hit most people don't know exists. rebase.autoSquash + autoStash + updateRefs — three settings that turn rebase from a ceremony into a one-liner. No manual stashing, automatic fixup folding, and all stacked branches move together. core.fsmonitor + untrackedCache — git status drops from hundreds of milliseconds to near-instant on large repos. A filesystem watcher replaces full directory scans. merge.conflictstyle = zdiff3 — conflict markers show three versions: yours, theirs, and the original. Once you see the common ancestor, the default style feels blind. push.autoSetupRemote + followTags — first push on a new branch, just git push. Tags travel with the code. No more -u origin branch-name, no more forgotten --tags. Full config with the story behind each section: https://lnkd.in/gymnYVQi Inspired by https://lnkd.in/g4KnmrQ9 #Git #CLI #DevTools #DeveloperProductivity
To view or add a comment, sign in
-
🚀 Today I learned: How to revert only specific files from a bad Git commit Earlier today, I made a mistake while working on a feature branch — I accidentally overwrote 31 important "workflow.json" files across two folders. The tricky part? I also had valid changes in the same branch that I needed to keep. A normal "git revert" would undo everything - good and bad. That’s when I discovered a much cleaner approach: a surgical revert that restores only the files you choose. Here’s the simple workflow I followed 👇 🔍 1. Find commits that touched the files git log --oneline -- 'path/to/folder/**/file.json' This filters history so you can quickly spot where things went wrong. 👀 2. Peek at file content from any commit git show <commit-id>:path/to/file.json No checkout needed — just inspect the file as it existed in the past. 📂 3. List exactly which files a bad commit changed git diff-tree --no-commit-id --name-only -r <bad-commit> -- 'path/**/*.json' This gave me a precise list of the 31 affected files. ♻️ 4. The magic command — restore only those files git checkout <good-commit-or-branch> -- file1 file2 file3 ... This pulls back only the selected files — everything else stays untouched. ✨ ✅ 5. Verify before committing git status --short git diff --cached I used to worry about “messing up Git,” but moments like this made me realize - Git is actually very forgiving when you know the right tools. If you're learning Git, this is a skill that will save you hours someday. #Git #SoftwareEngineering #LearningInPublic #DeveloperTips #VersionControl
To view or add a comment, sign in
-
-
Most developers use Git every day and still panic when something breaks. They copy-paste commands from Stack Overflow and hope for the best. I know because I did the same for years. Then I actually looked inside the .git folder. Here's what I found: Git is just a key-value database. It stores 4 types of objects - blobs, trees, commits, and tags. That's the entire system. Once I understood that, every confusing command started making sense. A few things that clicked for me: → A blob stores file content, not the filename, just the raw bytes. Same content = same hash = Git never stores duplicates. → A tree is a directory snapshot. It maps filenames to blob hashes and sub-trees. Your entire project is one tree object pointing to other trees and blobs. → A commit is not a diff. It's a full snapshot of your project at that moment, plus a pointer to the parent commit. That chain of pointers is your history. → A branch is literally a text file with a 40-character hash. That's it. When you commit, Git just updates that file to the new hash. → Detached HEAD isn't scary. It just means HEAD is pointing directly to a commit instead of a branch. Create a branch from there and you're fine. Once you see this, git rebase stops being magic. It's just: save your commits as patches → reset your branch to a new base → re-apply the patches. New hashes, same changes. And merge conflicts stop feeling random. Git is literally asking: "Both of you changed the same lines, which one is right?" I put this all together in a free PDF, 11 pages, dark theme, code examples throughout. Explains Git's internals from objects to branches to merge vs rebase, as simply as I could write it. Download it from this post. Save it for the next time someone on your team panics about a detached HEAD. #Git #SoftwareEngineering 11 pages covering: - Blob, Tree, Commit objects explained simply - Why branches are just text files - HEAD and Detached HEAD demystified - Staging area (the index) - actually explained - How merge and rebase work step-by-step - Common Git mistakes + how to fix them - Full cheat sheet
To view or add a comment, sign in
-
🧠 TIL: git update-index --skip-worktree - a tiny git flag that made my dev loop so much cleaner. Every project has those files - the ones that are tracked in the repo, but you need to tweak locally just to get a sane dev experience. For me today, it was two BullMQ processor files that spin up cron jobs (heartbeats, cache clearers) on every boot. Great in staging/prod. Annoying as heck when I'm just trying to debug something unrelated on my laptop. The catch: they're tracked files. So .gitignore doesn't help. .git/info/exclude doesn't help. The moment I comment out a scheduler to quiet things down, my git status lights up - and one stray git add . away from shipping a broken commit. The usual workaround is stash / pop - and it's genuinely painful: Before every branch switch → git stash After switching → git stash pop Forget once → you lose your local tweaks or hit merge conflicts on your own stash Multiple local tweaks across multiple files = a growing stash stack you have to babysit git status still nags you until you stash And good luck if you want to commit other changes without accidentally including these One line fixes all of that: git update-index --skip-worktree path/to/file Now git pretends the file matches the index. No more noise in status, no accidental add, no stash dance. Your local edits just… stay local. Forever. Silently. Undo is equally simple, whenever you want: git update-index --no-skip-worktree path/to/file One caveat worth knowing: if upstream ever changes that file, you'll need to --no-skip-worktree, stash, pull, and re-flag. But for files that rarely change upstream, it's a massive quality-of-life win. If you've ever muttered "why is this file showing up in my diff AGAIN" - give this a try. 🙌 Found this via this great little writeup: https://lnkd.in/g_JqgPG7 #git #developerproductivity #softwareengineering #TIL
To view or add a comment, sign in
-
Git 2.54 just dropped, and it’s a massive upgrade for our daily development workflows. 🚀 I’ve been exploring the latest release, and here are the 4 standout features that are officially changing how I manage my repositories: ✨ git history: Finally, a surgical, opinionated way to rewrite commit history. No more interactive rebases for simple typos or commit splits. ⚙️ Config-based hooks: Forget copying bash scripts into every .git/hooks folder. You can now manage hooks globally via your .gitconfig with local opt-outs. It’s clean, shareable, and scalable. 📈 Geometric Compaction: The new default maintenance strategy. It’s smarter, faster, and prioritizes daily performance over monolithic garbage collection. If you work in monorepos, this is a game-changer. 📊 git repo structure: Time to retire git-sizer. We now have native, detailed observability into our repository’s health—from commit depth to identifying the exact blobs bloating our disk space. Git 2.54 is a huge win for developer experience. If you’re looking to clean up your history, automate your quality checks, and keep your repos performant, it’s time to upgrade your git. #Git #DevOps #GitHub #SoftwareEngineering Read my deep dive into these Git features here -
To view or add a comment, sign in
-
Some basics of git ========================================================= Working Area: - the local directory on your computer where you can view and edit your project's files Staging Area (Index): You use the git add command to move specific changes from the working area to this intermediate "preparation" zone. Local Repository: You use git commit to permanently record the staged changes as a snapshot in the project's history. Common Commands git status: Shows which files in your working area have been modified but not yet staged, and which are untracked. git diff: Shows the exact line-by-line differences between your current working area and the staging area. git checkout -- <file>: Discards changes in your working area and restores the file to its last committed state. git stash - is a built-in Git command that temporarily saves your uncommitted changes so you can switch to a clean working directory without losing your work-in-progress. #git #github #jenkine #devops
To view or add a comment, sign in
-
Following a curious incident where a file with a problematic path ended up in Git history, even after deleting it in a later commit, it still stuck around in older commits and kept causing unexpected issues. At that point, just "removing it" isn’t really enough. If it exists anywhere in history, it can come back through merges, rebases, or even someone branching off an older commit. So the only reliable fix is to completely purge it from history. That’s where git filter-repo comes in. Read full post: https://lnkd.in/euktiC8f
To view or add a comment, sign in
-
The first thing we do when a new client engages us isn't opening their code. It's opening their git history. Before we read a single file, the commit log tells us most of what we need to know. Which parts of the codebase get touched every week? Those are the pain centers - the code everyone keeps patching but nobody fixes properly. Which parts haven't been modified in years? Those are the time bombs - either rock-solid foundations nobody needs to touch, or black boxes nobody dares to touch. You can usually tell the difference in under a minute. How do the commit messages look? "fix" "fix again" "hotfix prod" "please work" tells a very different story than clean, descriptive messages tied to feature branches. Does the team use feature branches at all? Or is everyone pushing straight to main and praying? Twenty minutes of reading git history and we already know where 80% of the problems live. No meetings. No slide decks. Just the data the codebase has been quietly recording about itself for years. Of course we also run automated checks - outdated libraries, oversized files, dependency vulnerabilities. And we talk to the team, because gut feeling from hundreds of projects fills in what the data can't. But git is our favourite part. It's the most honest member of any engineering team. It never exaggerates and it never hides anything. Have that stomach shake feeling thinking about your git log? Let's talk :)
To view or add a comment, sign in
-
-
The 5 Git Commands I Run Before Reading Any Code You’ll know which code to read first, and what to look for when you get there. That’s the difference between spending your first day reading the codebase methodically and spending it wandering. Git log --
To view or add a comment, sign in
-
I pick up a lot of codebases I didn't build. Before I open a single file, I run five git commands that give me a diagnostic picture of the project: where the risk is, who built it, whether the team is shipping with confidence. The commands themselves aren't exotic. What matters is what you look for in the output. Wrote up the five I run on every engagement, with what I'm actually interpreting at each step. https://lnkd.in/gu5QmxuP
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
✅ ANSWER: Ⓐ git checkout -- filename Why each option: Ⓐ git checkout -- filename (correct. Restores the file from the index to your working directory. In newer Git versions, git restore filename does the same thing with clearer intent.) Ⓑ git add filename (if the file is deleted, this stages the deletion. You're telling git "yes, I meant to delete this." The opposite of what you want.) Ⓒ git rm filename (confirms and stages the deletion. This is intentional removal, not recovery.) Ⓓ git recover filename (not a real git command.)