Console9

How to use .gitignore to exclude files

Exclude files and directories from Git tracking using .gitignore patterns and global ignore rules.

How to use .gitignore to exclude files

Exclude files and directories from Git tracking using .gitignore patterns and global ignore rules.

Prerequisites

  • Git installed with an initialized repository.

Step-by-Step: Configure .gitignore in Git

  1. Create a .gitignore file in the repository root:

    touch .gitignore
  2. Add patterns to exclude files. Git supports glob patterns, directory names, and negation:

    # Compiled files
    *.pyc
    *.o
    
    # Directories
    node_modules/
    __pycache__/
    .env/
    
    # Environment files
    .env
    *.secret
    
    # OS files
    .DS_Store
    Thumbs.db
    
    # Exception — track this specific file
    !config/.env.example
  3. Commit the .gitignore file:

    git add .gitignore
    git commit -m "Add .gitignore"
  4. Remove already-tracked files that should now be ignored:

    git rm --cached .env
    git commit -m "Stop tracking .env file"