This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of separate Git repositories, or one repository where each top-level directory gets its own commit. Below the original script you will find what is wrong with it, a corrected version for each case, and the errors you are most likely to see when you run them.
This script will loop through each directory in the repository, checking if it is a Git repository. If it is, it will add all changes in the directory, commit them with a message that includes the directory path, and push the changes to the remote repository. Note that this script assumes that the repository is structured such that each directory is a separate Git repository.
Two different problems behind the same title
"Commit each directory at a time" can mean two things, and they need different scripts:
| Layout | What you want | Script to use |
|---|---|---|
A parent folder (for example ~/projects) containing many independent repositories | Commit and push every repository in one run | Script A: multi-repository loop |
One repository with several top-level folders (for example frontend/, backend/, infra/) | One commit per folder so the history stays readable, then push | Script B: one commit per directory |
The script above is aimed at the first layout, but it starts with git rev-parse --show-toplevel. That command only works inside a repository, so the script fails in exactly the layout it was written for.
What is wrong with the original script
- It needs a parent repository.
git rev-parse --show-toplevelexits withfatal: not a git repositorywhen it runs in a plain folder that holds several repositories. - Paths with spaces break it.
for dir in $(find ...)splits the output on whitespace and expands glob characters, soMy Projectturns into two invalid paths. - It walks inside
.git.find -type dlists every folder under every.gitdirectory, often thousands of them, and runscdinto each one for nothing. - It ignores failed
cdcommands. Ifcd "$dir"fails, the Git commands that follow run in whatever folder the script happens to be in. - It misses some repositories.
[ -d .git ]is false for submodules and linked worktrees, because there.gitis a file, not a folder. - It assumes every repository has changes and an upstream. In a clean repository,
git commitexits with an error. On a new branch with no upstream,git pushfails. - It has stray comment lines. Generated text was pasted into the code as comments. They are harmless but make the script harder to read.
Script A: commit and push every repository under a folder
This version uses find ... -print0 together with read -d '', so any file name works, spaces included. -prune stops find from looking inside .git. git -C runs each command in the target repository without any cd.
#!/usr/bin/env bash
# Commit and push every Git repository found under a parent directory.
# Usage: ./commit-all-repos.sh [parent_dir] [commit message]
set -uo pipefail
base_dir="${1:-.}"
message="${2:-Automated commit}"
failed=()
while IFS= read -r -d '' git_entry; do
repo="$(dirname "$git_entry")"
echo "==> $repo"
# Commit only if there are tracked or untracked changes
if [ -n "$(git -C "$repo" status --porcelain)" ]; then
git -C "$repo" add -A &&
git -C "$repo" commit -q -m "$message ($(basename "$repo"))" ||
{ failed+=("$repo (commit)"); continue; }
else
echo " no local changes"
fi
# Skip push on a detached HEAD
branch="$(git -C "$repo" symbolic-ref --quiet --short HEAD)" ||
{ echo " detached HEAD, skipping push"; continue; }
if git -C "$repo" rev-parse --quiet --verify '@{u}' >/dev/null 2>&1; then
git -C "$repo" push -q || failed+=("$repo (push)")
elif git -C "$repo" remote get-url origin >/dev/null 2>&1; then
git -C "$repo" push -q -u origin "$branch" || failed+=("$repo (push)")
else
echo " no remote 'origin', skipping push"
fi
done < <(find "$base_dir" -name .git -prune -print0)
if [ "${#failed[@]}" -gt 0 ]; then
printf 'FAILED: %s\n' "${failed[@]}" >&2
exit 1
fi
echo "All repositories processed."Code language: PHP (php)
find "$base_dir" -name .git -prune -print0finds each.gitentry, whether it is a folder or a file, and does not descend into it.git status --porcelainprints nothing when the repository is clean, so clean repositories skip the commit and do not produce an error.rev-parse --verify '@{u}'checks whether the current branch has an upstream. If it does not, the script pushes with-u origin <branch>to create one.- Failures are collected in
failedinstead of stopping the run. The script exits with status 1 at the end if any repository failed, which suits cron jobs and CI.
Script B: one commit per directory inside a single repository
Use this when everything lives in one repository and you want a separate commit for each top-level folder. It pushes once at the end, which sends all the new commits together.
#!/usr/bin/env bash
# Create one commit per top-level directory, then push once.
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
for dir in */; do
dir="${dir%/}"
[ -d "$dir" ] || continue # no subdirectories at all
# Skip folders with no changes (also skips ignored and empty folders)
[ -n "$(git status --porcelain -- "$dir")" ] || continue
git add -A -- "$dir"
git commit -q -m "Update $dir" -- "$dir"
echo "Committed $dir"
done
git pushCode language: PHP (php)
git add -A -- "$dir"stages new, changed and deleted files, but only inside that folder.git commit ... -- "$dir"commits only that path, so changes you staged elsewhere earlier do not slip into the wrong commit.*/does not match hidden folders such as.github/, and files in the repository root are not committed. Add a finalgit add -A && git commit -m "Update root files"if you need those too.- To push after each commit instead of once at the end, move
git pushinside the loop.
Running the scripts
- Save the script, for example as
commit-all-repos.sh, and make it executable:chmod +x commit-all-repos.sh. - Check what will be committed before the first run. For Script A:
for d in */; do echo "== $d"; git -C "$d" status -s 2>/dev/null; done. For Script B:git status -s. - Make sure pushes work without a prompt: an SSH key loaded in your agent, or an HTTPS credential helper with a token.
- Run it. Script A:
./commit-all-repos.sh ~/projects "Nightly sync". Script B: run it from anywhere inside the repository. - Confirm the result with
git log --oneline -5in one of the repositories.
==> /home/dev/projects/api
==> /home/dev/projects/docs
no local changes
==> /home/dev/projects/scratch
no remote 'origin', skipping push
All repositories processed.Code language: JavaScript (javascript)
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
fatal: not a git repository | The original script was run from a folder that is not a repository | Use Script A, which does not need a parent repository |
nothing to commit, working tree clean | git commit ran in a repository with no changes | Check git status --porcelain first, as both scripts do |
fatal: The current branch has no upstream branch | A new local branch was never pushed | Push with git push -u origin <branch>. Script A does this automatically |
Author identity unknown | user.name or user.email is not set | Run git config --global user.name "Name" and git config --global user.email you@example.com |
! [rejected] ... (fetch first) | The remote has commits you do not have locally | Run git pull --rebase in that repository, then run the script again |
Permission denied (publickey) | No SSH key is available, which is common under cron | Load the key in ssh-agent or set GIT_SSH_COMMAND to point at a key file |
Safety notes
git add -Acommits everything that.gitignoredoes not exclude, including.envfiles, credentials and build output. Check each repository's.gitignorebefore you automate this.- Automatic commits with generic messages make history hard to read. Keep these scripts for sync and backup repositories, not for shared code that people review.
- Never add
--forceto the push in a bulk script. One bad run could overwrite other people's work in every repository at once. - For large trees, add
-maxdepth 3to thefindcommand, or exclude folders such asnode_modules, to keep Script A fast.
Note: Branching, rebasing and pull-request flows are covered in the Git Workflow Master Tutorial.
Frequently asked questions
How do I commit and push all Git repositories in a folder at once?
Loop over every .git entry found by find <folder> -name .git -prune -print0. For each one, run git -C <repo> add -A, commit and push, as Script A does. This handles spaces in paths and skips repositories that have no changes.
How do I make a separate commit for each folder in one repository?
For each folder, run git add -A -- <folder> and then git commit -m "..." -- <folder>. Run git push once at the end. Adding the path after -- limits each commit to that folder.
Why does my bulk push script fail with 'no upstream branch'?
A branch that has never been pushed has no remote tracking branch, so a plain git push does not know where to send it. Push once with git push -u origin <branch>, or let the script detect the missing upstream and do it for you.
Can I run this script from cron?
Yes, as long as Git can authenticate without a prompt and the commit identity is configured. That means an SSH key with no passphrase or a running agent, or an HTTPS credential helper. Use absolute paths, and send output to a log file so you can check failures later.
Does git add -A include deleted files?
Yes. git add -A stages new, modified and deleted files. Adding a path after -- limits that to the given folder.
Related tutorials
- Git Workflow Master Tutorial
- What is Git and use cases of Git?
- Top 50 Interview question And answers of Git
- More Git tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals