0
0
Gitdevops~5 mins

git add with patterns and directories - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you change files in a project, you need to tell Git which files to save for the next snapshot. Using patterns and directories with git add helps you quickly select many files without naming each one.
When you want to add all files in a folder to your next commit.
When you want to add only files with a certain extension, like all .txt files.
When you want to add files that match a pattern, like all files starting with 'test'.
When you want to add changes in multiple folders at once.
When you want to avoid adding unwanted files by specifying exactly which files to include.
Commands
This command adds all files and folders inside the 'docs' directory to the staging area, preparing them for the next commit.
Terminal
git add docs/
Expected OutputExpected
No output (command runs silently)
This adds all files ending with .txt in the current directory to the staging area. The quotes prevent the shell from expanding the pattern before Git sees it.
Terminal
git add '*.txt'
Expected OutputExpected
No output (command runs silently)
This adds all JavaScript files inside the 'src' directory to the staging area.
Terminal
git add src/*.js
Expected OutputExpected
No output (command runs silently)
This adds all files and folders starting with 'test' in the current directory to the staging area.
Terminal
git add 'test*'
Expected OutputExpected
No output (command runs silently)
Shows which files are staged and ready to be committed, confirming that the correct files were added.
Terminal
git status
Expected OutputExpected
On branch main Changes to be committed: (use "git restore --staged <file>..." to unstage) new file: docs/readme.md new file: notes.txt new file: src/app.js new file: test_script.sh
Key Concept

If you remember nothing else from this pattern, remember: git add can use folder names and file patterns to quickly select many files at once.

Common Mistakes
Not using quotes around patterns like '*.txt'
The shell expands the pattern before Git sees it, which can cause errors or no files added if no matches exist.
Always put quotes around patterns to let Git handle the matching.
Trying to add a directory without a trailing slash
Git may not recognize it as a directory and fail to add its contents.
Always include the trailing slash when adding directories, like 'git add docs/'.
Adding too broad a pattern and including unwanted files
You might stage files you did not intend to commit, causing confusion or errors.
Use specific patterns or check with 'git status' before committing.
Summary
Use 'git add directory/' to stage all files inside a folder.
Use 'git add "*.ext"' with quotes to stage files matching a pattern.
Check staged files with 'git status' before committing.