Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Git & GitHub - Git Ignore

How to use .gitignore files

The .gitignore file tells Git which files or directories to ignore in a project. This guide explains how to use .gitignore files to prevent unnecessary files from being tracked in your Git repository.

Key Points:

  • .gitignore files specify which files and directories Git should ignore.
  • Patterns in the .gitignore file define the files to be ignored.
  • Ignoring unnecessary files helps keep your repository clean and reduces clutter.

Creating a .gitignore File

To create a .gitignore file, simply create a new file named .gitignore in the root directory of your repository.


# Create a .gitignore file
$ touch .gitignore
                

Defining Patterns in .gitignore

You can define patterns in the .gitignore file to specify which files and directories Git should ignore. Here are some common patterns:


# Ignore all .log files
*.log

# Ignore all files in the temp directory
temp/

# Ignore specific file
secret.txt

# Ignore node_modules directory
node_modules/

# Ignore all .env files
*.env
                

Ignoring Tracked Files

If you want to stop tracking a file that is already being tracked by Git, first add the file to the .gitignore file, then use the git rm --cached command to untrack the file.


# Add the file to .gitignore
echo 'tracked_file.txt' >> .gitignore

# Untrack the file
$ git rm --cached tracked_file.txt
                

This command removes the file from the staging area but leaves it in the working directory.

Global .gitignore

You can create a global .gitignore file to apply ignore rules to all Git repositories on your system. First, create a global .gitignore file, then configure Git to use it.


# Create a global .gitignore file
$ touch ~/.gitignore_global

# Configure Git to use the global .gitignore file
$ git config --global core.excludesfile ~/.gitignore_global
                

Add your global ignore rules to the .gitignore_global file.

Useful .gitignore Templates

There are many useful .gitignore templates available for different programming languages and frameworks. You can find these templates on GitHub: github/gitignore.


# Download a template .gitignore file for Node.js
$ curl https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore -o .gitignore
                

Summary

This guide covered how to use .gitignore files to prevent unnecessary files from being tracked in your Git repository. By defining patterns in the .gitignore file, you can keep your repository clean and focused on the relevant files.