EDDYMENS

Published 3 days ago

GIT | How To Ignore The Contents Of A Folder But Not The Folder Itself

Table of contents

You may already be familiar with the .gitignore file, which allows you to specify the files and folders that you want Git to ignore or stop tracking.

However, in the case of a directory, simply specifying the folder name will cause Git to ignore both the folder and its contents.

However, there may be situations where you want to track the folder itself but not its contents. In such cases, you need to make an additional entry in your .gitignore file.

For example, lets say you have a logs folder where your application stores log files. As you might expect, you would want to keep the logs folder in the repository, but you would prefer not to track its contents.

Ignoring the future contents of a newly created folder

If the folder you want to ignore does not yet contain any files, you should create a .gitignore file inside it. Since Git does not track empty folders, adding a .gitignore file ensures the folder is tracked while also allowing you to specify ignore instructions for its contents.

01: mkdir logs 02: touch logs/.gitignore

Contents of the .gitignore file is as follows:

.gitignore

01: * 02: !.gitignore

You can have multiple .gitignore files within a project. This means you can create a separate .gitignore file outside the folder to manage ignore rules for other files and folders in your project.

Ignoring an already committed folder and its contents

If the folder and its contents have already been committed to your repository but you now want to ignore the files, you will first need to create a .gitignore file. While you can create this file outside the folder, it is generally better to create it inside the folder itself, for example: logs/.gitignore.

Your .gitignore file should include the following:

.gitignore

01: logs/* 02: !logs

To stop tracking previously committed files, you need to clear the Git cache for those files. This process removes them from the Git index without deleting them from your local file system.

$ git rm -r --cached logs/

Do note that clearing the Git cache will not remove the files from the repository's history. Instead, it ensures that the files are ignored in future commits.

Finishing up

After clearing the Git cache and updating your .gitignore file, you can proceed to commit your changes:

01: git add --all 02: git status # Displays the list of files that have been staged, modified, or remove 03: git commit -m "ignore log files"

Here is another article you might like 😊 How To Use Rsync To Sync Files Between Servers While Excluding Specific Folders