Working with Multiple Files and Directories
Now that we know how to remove a single file from Git's cache, let's explore more complex scenarios like removing multiple files or entire directories.
Creating More Files for Practice
Let's first create a few more files and a directory structure to practice with:
- Create a directory and some additional files:
## Create a directory for temporary files
mkdir temp
## Create some files in the temp directory
echo "This is a temporary file" > temp/temp1.txt
echo "Another temporary file" > temp/temp2.txt
## Create another log file in the main directory
echo "2023-01-02: System updated" > system.log
- Add these new files to Git's tracking:
git add .
- Commit the changes:
git commit -m "Add temporary files and system log"
- Verify that Git is tracking all files:
git ls-files
You should see:
config.ini
sample.txt
system.log
temp/temp1.txt
temp/temp2.txt
Removing Multiple Files from Git's Cache
Now let's say we want to remove all log files and the entire temp directory from Git's tracking.
- Remove the log file from Git's tracking:
git rm --cached system.log
- Remove all files in the temp directory recursively:
git rm --cached -r temp/
The -r
flag is important here as it tells Git to recursively remove all files in the directory from its cache.
- Check the status:
git status
You'll see that both the log file and all files in the temp directory are staged for deletion from Git's tracking system:
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
deleted: system.log
deleted: temp/temp1.txt
deleted: temp/temp2.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
app.log
system.log
temp/
- Commit these changes:
git commit -m "Remove logs and temp directory from Git tracking"
- Verify that Git is no longer tracking these files:
git ls-files
Now you should only see:
config.ini
sample.txt
However, all files still exist in your local directory:
ls -la
ls -la temp/
Using .gitignore to Prevent Tracking Unwanted Files
Now that we've removed the files from Git's tracking, let's set up a .gitignore
file to prevent them from being accidentally added again:
- Create a
.gitignore
file:
nano .gitignore
- Add the following patterns to the file:
## Ignore log files
*.log
## Ignore temp directory
temp/
-
Save and exit (press Ctrl+X, then Y, then Enter)
-
Add and commit the .gitignore
file:
git add .gitignore
git commit -m "Add .gitignore file"
Now, even if you try to add all files to Git, it will respect your .gitignore
file and not track the specified patterns:
git add .
git status
You should see that the log files and temp directory are not being added to Git's tracking.
You've now learned how to remove multiple files and directories from Git's cache and how to prevent specific files from being tracked in the future using a .gitignore
file.