Exclude files from git revision without adding to .gitignore
Have you ever wanted to create some file(s) in your repo but do not want it to commit or show in the git changes?
Your first thought would be to mention that file in .gitignore and commit it, but what if I told you there's a way without even adding it to your repo's .gitignore:
Per repository basis
Approach 1: Using .git/info/exclude file
This approach allows you to ignore individual files at the root of the repository or any specific files and directories without modifying the .gitignore file. Changes made in the .git/info/exclude file are local to your repository and won't affect other collaborators.
For example, if you want to ignore a file named mynotes.md:
-
Open the
.git/info/excludefile in your repository:nano .git/info/exclude -
Add the patterns of the files and directories you want to ignore. In this case, to ignore
mynotes.md, you would add:mynotes.md -
Save and close the file. In Nano, you can save by pressing
Ctrl+Oand thenEnter. Close the editor withCtrl+X. -
Verify the ignored files by running
git status. Themynotes.mdfile should no longer appear in the list of untracked files.
Approach 2: Using a .gitignore file inside a directory
This approach is effective for ignoring entire directories and their contents without modifying the main .gitignore file in the root of the repository. It is useful for keeping ignore rules specific to a directory, especially when you don't want these rules to be tracked or shared.
Let's suppose you want to have a folder drafts and ignore it and everything in it from git:
- Create a folder
draftsin your repo. - Add some files to it.
- Those files will currently show as untracked files when running
git status. - Now, create a
.gitignorefile insidedraftsand write in it. This means all files insidedraftswill be ignored.-
You can create as many files or folders inside
draftsand they won't show up in git changes. -
Next time, you can use this one-liner command to create a
draftsfolder and put a.gitignorefile:mkdir drafts && echo '*' > ./drafts/.gitignore
-
For all repositories
- We'll be using a global
.gitignorefor it that takes higher precedence over a repo's.gitignorefile. - let's suppose you want to hide
.DS_Store,.env.productionfiles from all current and future repo's:-
changes directory to
/Users/{User}cd ~
-
create an empty file with .gitignore
- Mac:
touch .gitignore - Windows:
type nul > .gitignoreorecho.> .gitignore
- Mac:
-
Tell git to use that file as global ignore
git config --global core.excludesfile ~/.gitignore
-
open this
.gitignorefile:- Mac:
open -a TextEdit ~/.gitignore - Windows:
notepad ~/.gitignore
- Mac:
-
and mention files (or patterns) to ignore:
.DS_Store .env.production
-
