#!/usr/bin/env bash # next_numbered_dir — Compute the next NNNN- prefix for a numbered directory. # # Scans the DIRECT subdirectories of whose names start with a # numeric prefix of the form `NNNN-` (4+ digits followed by a hyphen), takes # the maximum number, adds 1, and prints it zero-padded to (default 4). # If does not exist or contains no matching subdir, prints the # first number (0001 at default width). next_numbered_dir() { local parent_dir="${1:-}" local width="${2:-4}" if [[ -z "$parent_dir" ]]; then echo "usage: next_numbered_dir [width]" >&2 return 1 fi local max=0 local entry base num if [[ -d "$parent_dir" ]]; then # Iterate only over direct subdirectories. The trailing slash in the # glob ensures files (e.g. .gitkeep) are skipped — only dirs match. for entry in "$parent_dir"/*/; do # If the glob matched nothing it stays literal; guard with -d. [[ -d "$entry" ]] || continue base="$(basename "$entry")" # Require a prefix of 4+ digits followed by a hyphen. if [[ "$base" =~ ^([0-9]{4,})- ]]; then num="${BASH_REMATCH[1]}" # Force base 10 so leading zeros (08, 09) are not read as octal. num=$((10#$num)) if (( num > max )); then max=$num fi fi done fi printf "%0*d\n" "$width" $(( max + 1 )) } if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then next_numbered_dir "$@" fi