Git is a popular distributed version control system used by teams all over the world. While working with a git repository, you may need to exclude or ignore certain files and folders because you may not need to push them to your repository. This may happen in case those changes are relevant locally but not important for other developers who use your repository. In such cases, it is advisable to exclude those files & folders from git commit. In this article, we will look at how to exclude files in git commit.
How to Exclude File in Git Commit
Here are the steps to exclude file in git commit. git allows you to create a .gitignore file which basically lists all the files and folders that need to be excluded. When you run git commands like git status or git commit, it will scan the .gitignore file contents to exclude files & folders that match the patterns mentioned in that file. You can add this file in the root directory of your git repository or any of the sub directories. You can also place multiple .gitignore files across different sub directories, instead of placing one file at the root folder.
1. Create .gitignore file
Let us say your repository is located at /home/ubuntu/demo. Open terminal and run the following command to create a .gitignore file at the root folder.
$ sudo vi /home/ubuntu/demo/.gitignore
Also read : How to Undo Git Commit
2. Add files and folders to be excluded
Add the files and folders you want to exclude, one on each line. You can specify relative paths to your files & folders. Or you can use wildcard characters and regex patterns like * to list them. Here are the commonly used wildcard characters.
- ** – prepend double asterisk before folder name to directories anywhere in the repository
- * – single asterisk matches zero or more characters
- ! – prepending exclamation mark to file & folder names negates its exclusion, that is, they won’t be excluded.
- / – prepending slash indicates the directory where .gitignore is placed
- # – used to add comments
Also read : How to Save Iptables rules permanently
Let us look at sample .git ignore file, with commends explaining what each line excludes
# excludes all .log files in the repository *.log # but does not exclude key.log !key.log # exclude any directory containing pdf in its path such as /demo/pdf and /demo/test/pdf/share **pdf #exclude debug0.log to debug9.log debug[0-9].log #exclude all .txt files in present directory /*.txt
Save and close the file. Each pattern in .gitignore file is examined with respect to the folder in which it is placed.
That’s it. Now when you commit files & folders to git repository, it will automatically exclude the ones mentioned in your .git ignore file.