Our thinking


Count Files

This script will count the files in the current directory and all the subdirectories – it’s useful for checking if you have sync issues with Dropbox as Dropbox seems to flip out once you have more than around 300k – 400k files, irrespective of the total size of the files.

#!/bin/bash

# ANSI escape sequences for bold text
bold=$(tput bold)
normal=$(tput sgr0)

# Function to count files recursively
count_files_recursive() {
  local directory="$1"
  local file_count=$(find "$directory" -type f | wc -l)
  echo "$file_count"
}

# Declare arrays to store directory names and file counts
dirs=()
file_counts=()

# Iterate over directories in the current working directory
for dir in */; do
  # Remove trailing slash from directory name
  dir="${dir%/}"

  # Exclude symbolic links
  if [ ! -L "$dir" ]; then
    # Count the files in the directory
    file_count=$(count_files_recursive "$dir")

    # Store the directory name and file count in arrays
    dirs+=("$dir")
    file_counts+=("$file_count")
  fi
done

# Get the length of the arrays
length=${#dirs[@]}

# Sort the directory names based on file counts in descending order
for ((i=0; i<$length-1; i++)); do
  for ((j=$i+1; j<$length; j++)); do
    if [ "${file_counts[$j]}" -gt "${file_counts[$i]}" ]; then
      # Swap directory names
      temp=${dirs[$i]}
      dirs[$i]=${dirs[$j]}
      dirs[$j]=$temp

      # Swap file counts
      temp=${file_counts[$i]}
      file_counts[$i]=${file_counts[$j]}
      file_counts[$j]=$temp
    fi
  done
done

# Iterate over sorted directories and print the directory name and file count
for ((i=0; i<$length; i++)); do
  dir=${dirs[$i]}
  file_count=${file_counts[$i]}

  # Format the file count with thousands separators
  formatted_count=$(printf "%'d" "$file_count")

  # Check if file count exceeds 10,000
  if [ "$file_count" -gt 10000 ]; then
    # Print directory name in bold
    echo -e "${bold}Directory: $dir${normal}"
    # Print file count in bold
    echo -e "${bold}File count: $formatted_count${normal}"
  else
    echo "Directory: $dir"
    echo "File count: $formatted_count"
  fi

  echo "-------------------"
done

Leave a Reply