Skip to content

Instantly share code, notes, and snippets.

@miaLDN
Last active April 26, 2026 01:06
Show Gist options
  • Select an option

  • Save miaLDN/0130858425286dc886d53b8fe83d6633 to your computer and use it in GitHub Desktop.

Select an option

Save miaLDN/0130858425286dc886d53b8fe83d6633 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# shellcheck shell=bash
# ----------------------------------------------------------------
# Name: find_and_shorten (Recursive Byte-level Truncate)
# Version: 1.3.1
# (C) miaLDN 2026
# ----------------------------------------------------------------
source "${HOME}/.local/bin/ansi_colors.sh"
MAX_TOTAL_BYTES=143 # eCryptFS max bytes in filename
COMMIT=false
TARGET_DIR="."
while [[ $# -gt 0 ]]; do
case $1 in
-y|-yes|--yes) COMMIT=true; shift ;;
*) TARGET_DIR="$1"; shift ;;
esac
done
# Depth-first is the 'Bottom-Up' standard
find "$TARGET_DIR" -depth -print0 \
| while IFS= read -r -d '' path; do
[[ "$path" == "$TARGET_DIR" ]] && continue
clean_path="${path#./}"
dir=$(dirname "$clean_path")
base=$(basename "$clean_path")
# Only files get extension preservation
if [[ -f "$path" && "$base" == *.* ]]; then
ext=".${base##*.}"
name="${base%.*}"
else
ext=""
name="$base"
fi
ext_bytes=$(echo -n "$ext" | wc -c)
max_name_bytes=$(( MAX_TOTAL_BYTES - ext_bytes ))
# Byte-level slice for eCryptfs compatibility
short_name=$(echo -ne "$name\0" | cut -z -b 1-"$max_name_bytes" | xargs -0)
new_base="${short_name}${ext}"
final_bytes=$(echo -n "$new_base" | wc -c)
if [[ "$base" != "$new_base" ]]; then
if [ "$COMMIT" = true ]; then
if mv --no-clobber "$path" "${dir}/${new_base}"; then
echo -e "${BLUE_B}RENAMED:${ANSI_DEFAULT} ${YELLOW1_TEXT}'$base'${ANSI_DEFAULT} (${BOLD_RED}${final_bytes}b${ANSI_DEFAULT})"
else
echo -e "${BOLD_RED}COLLISION:${ANSI_DEFAULT} Skipped '$base'"
fi
else
# Ligature-ready >> and High-Viz BOLD_RED
echo -e "${ORANGE_B}DRY RUN:${ANSI_DEFAULT} ${YELLOW1_TEXT}'$base'${ANSI_DEFAULT} ${BLUE_TEXT}>>${ANSI_DEFAULT} ${GREEN1_TEXT}'$new_base'${ANSI_DEFAULT} (${BOLD_RED}${final_bytes}b${ANSI_DEFAULT})"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment