To ignore certain files or folders in Git, you can use the .gitignore file. Here are detailed steps and examples:
-
Create the
.gitignorefile Create a.gitignorefile in the root directory of your Git repository. If one already exists, simply edit it. -
Edit the
.gitignorefile Open the.gitignorefile and add rules to specify which files or folders to ignore. Each line represents a rule. -
.gitignorerules examples- Ignore all
.logfiles:*.log - Ignore a specific file:
/todo.txt(ignorestodo.txtin the root directory) - Ignore a specific folder:
temp/(ignores thetempfolder and its contents) - Ignore all files except a specific one:
/*(ignores all files) and!/README.md(excludesREADME.mdfrom being ignored) - Ignore specific files in nested folders:
build/logs/(ignores all files in thelogsfolder within thebuildfolder) - Ignore all folders except a specific one:
/*(ignores all top-level folders) and!/keep-this-folder/(preserves thekeep-this-folderfolder)
- Ignore all
-
Commit the
.gitignorefile to the repository Add and commit the.gitignorefile using the following command:shgit add .gitignore git commit -m "Add .gitignore file" -
Check ignored files To view which files are currently ignored by
.gitignore, use the following command:shgit status --ignored -
Exception rules If you have already ignored certain files in
.gitignorebut need to track a specific file, use the!prefix to specify it.Note: If you have manually tracked files that are specified to be ignored in
.gitignore, they will not be automatically ignored. In this case, you need to remove them from the Git repository but keep their local copies. Use the following command:shgit rm --cached FILENAMEAfter this, these files will be ignored by
.gitignore.
This is how to ignore files in Git. It is very useful for preventing sensitive data, compiled outputs, log files, and other content that should not be committed to version control from being included.