MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Shell script to git add and commit and push each directory at a time

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:

LayoutWhat you wantScript to use
A parent folder (for example ~/projects) containing many independent repositoriesCommit and push every repository in one runScript 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 pushScript 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-toplevel exits with fatal: not a git repository when 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, so My Project turns into two invalid paths.
  • It walks inside .git. find -type d lists every folder under every .git directory, often thousands of them, and runs cd into each one for nothing.
  • It ignores failed cd commands. If cd "$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 .git is a file, not a folder.
  • It assumes every repository has changes and an upstream. In a clean repository, git commit exits with an error. On a new branch with no upstream, git push fails.
  • 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 -print0 finds each .git entry, whether it is a folder or a file, and does not descend into it.
  • git status --porcelain prints 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 failed instead 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 final git 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 push inside the loop.

Running the scripts

  1. Save the script, for example as commit-all-repos.sh, and make it executable: chmod +x commit-all-repos.sh.
  2. 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.
  3. Make sure pushes work without a prompt: an SSH key loaded in your agent, or an HTTPS credential helper with a token.
  4. Run it. Script A: ./commit-all-repos.sh ~/projects "Nightly sync". Script B: run it from anywhere inside the repository.
  5. Confirm the result with git log --oneline -5 in 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

ErrorCauseFix
fatal: not a git repositoryThe original script was run from a folder that is not a repositoryUse Script A, which does not need a parent repository
nothing to commit, working tree cleangit commit ran in a repository with no changesCheck git status --porcelain first, as both scripts do
fatal: The current branch has no upstream branchA new local branch was never pushedPush with git push -u origin <branch>. Script A does this automatically
Author identity unknownuser.name or user.email is not setRun 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 locallyRun git pull --rebase in that repository, then run the script again
Permission denied (publickey)No SSH key is available, which is common under cronLoad the key in ssh-agent or set GIT_SSH_COMMAND to point at a key file

Safety notes

  • git add -A commits everything that .gitignore does not exclude, including .env files, credentials and build output. Check each repository's .gitignore before 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 --force to 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 3 to the find command, or exclude folders such as node_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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Bash Git Aliases: A Practical Command Set for Faster Daily Git Work

Set up a clean, copy-paste-ready Bash alias collection for common Git commands, then learn when Bash aliases are better than Gitโ€™s built-in aliases. This guide also covers safe installation, workflow usage, and common mistakes to avoid.

Read More

Shell script to add and commit in 10 files at a time and push

Rajesh Kumar 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…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

AWS Tutorials: Working with Code Commit

AWS CodeCommit is a managed, private Git hosting service. You create a repository in a Region, sign in with IAM-based credentials, and then use normal Git commands…

Read More

Shell Bash Scripting: Assignment & Excercise – 7

This exercise uses Bash, rsync and SSH to copy a local file to a remote backup server, then sends an email when the copy finishes. Below the…

Read More

Git Lab Exercise & Assignment: Git cherry-pick: Part – 12

git cherry-pick copies one or more existing commits from another branch and applies them as new commits on your current branch. This lab corrects and completes the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x