Mirror of
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add guide for untracking files with .gitignore (#178)

authored by

Felix Schneider and committed by
GitHub
4df2cedc f326b618

+35
+35
src/content/docs/blog/uncommon-git-commands.mdx
··· 96 96 This is a destructive action. Therefore I included a safeguard by using the lowercase `-d` parameter. If your branches are not cleanly merged, git will not delete them. If you are sure you want to delete all those branches no matter what, use `-D` instead. 97 97 ::: 98 98 99 + ## Remove tracked files with .gitignore 100 + 101 + We’ve all been there: you create a `config.json` or a `.env` file, write some code, and commit it. Later, you realize that file should definitely not be in the repository, so you add it to your `.gitignore`. 102 + 103 + The problem? Git is already tracking it. Adding a file to `.gitignore` only stops Git from tracking *new* files. To tell Git to "forget" a file it is already tracking without deleting it from your hard drive, you use the `--cached` flag: 104 + 105 + ```bash 106 + git rm --cached <file_path> 107 + ``` 108 + 109 + If you accidentally committed an entire directory (like `node_modules` or `dist`), you can do it recursively: 110 + 111 + ```bash 112 + git rm -r --cached <folder_name>/ 113 + ``` 114 + 115 + If your repository has become a bit of a mess and you want to "reset" the tracking for everything to strictly follow your current `.gitignore` rules, run this sequence from the repository root: 116 + 117 + ```bash 118 + git rm -r --cached . 119 + git add . 120 + git commit -m "Refactor: apply .gitignore to all tracked files" 121 + ``` 122 + 123 + This removes everything from the index and adds it all back. Because the files are now in your `.gitignore`, Git will simply skip over them during the `add` step, effectively untracking them. 124 + 125 + :::caution 126 + If the file contained secrets, untracking it is not enough. The secret is still present in earlier commits and may already be on the remote, so rotate the secret and consider rewriting history as well. 127 + ::: 128 + 99 129 ## Summary 100 130 101 131 **🛰️ Track Upstream Branch** ··· 112 142 > `git fetch -p && git branch -vv | awk '/: gone] / {print $1}' | grep -v '^\*$' | xargs -I{} git branch -d "{}"` 113 143 > 114 144 > A pipeline that identifies local branches whose remote counterparts have been deleted ("gone") and attempts to delete them safely. 145 + 146 + **🧺 Untrack "Ignored" Files** 147 + > `git rm --cached <file>` 148 + > 149 + > Removes files from the Git index while keeping them physically on your disk. Essential for when you added a file to `.gitignore` after it was already committed. 115 150 116 151 ## Resources 117 152