[Login]

scripts/git each

#!/bin/bash

# Runs a git command on all subdirectories that are git repos
# Usage: git each <command>
# Example: git each status

RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
NC=$(tput sgr0)

dirs=(*/)

repo_count=0

for dir in "${dirs[@]}"; do
  # Make sure #dir is a git repo, if not, skip it
  branch=$(git -C "$dir" rev-parse --abbrev-ref HEAD 2>/dev/null)
  if [[ -z "$branch" ]]; then
    continue
  fi

  repo_count=$[$repo_count +1]
 
  echo ""
  echo "${GREEN}---------------------------------------------------------------"
  echo "$(tput bold)${YELLOW}$branch:${GREEN} $(tput bold)${dir%/}$(tput sgr0)${GREEN}"
  echo "---------------------------------------------------------------${NC}"

  # Execute the command. -C means to execute the command in the supplied path
  git -C "$dir" "$@"

  # Make sure the git command was successful, if not, exit
  status=$?
  if [ $status -ne 0 ]; then
    exit $status
  fi
done

if [[ $repo_count == 0 ]]; then
  echo "${RED}No git repos found${NC}"
  exit 1
fi