Skip to content

Instantly share code, notes, and snippets.

@CalebCurry
Created August 7, 2025 19:34
Show Gist options
  • Save CalebCurry/02405ed1d2fcb7d96c093bec9048355e to your computer and use it in GitHub Desktop.
Save CalebCurry/02405ed1d2fcb7d96c093bec9048355e to your computer and use it in GitHub Desktop.
Run handbrakecli for new published files
#!/bin/bash
# Custom paths you asked for
SOURCE_DIR="$HOME/Movies/final"
OUTPUT_DIR="$HOME/handbraked"
PROCESSED_DIR="$SOURCE_DIR/processed"
LOG_FILE="$OUTPUT_DIR/compression_failures.log"
LOCK_FILE="$OUTPUT_DIR/.compress_lock"
# Check if script is already running
if [ -f "$LOCK_FILE" ]; then
echo "Script already running. Exiting."
exit 0
fi
# Create lock file
echo $$ > "$LOCK_FILE"
# Remove lock file on exit
trap 'rm -f "$LOCK_FILE"' EXIT
# Ensure required folders exist
mkdir -p "$OUTPUT_DIR"
mkdir -p "$PROCESSED_DIR"
echo "πŸ“¦ Scanning for files in: $SOURCE_DIR"
# Check if there are any files to process
files_found=false
for f in "$SOURCE_DIR"/*
do
[ -f "$f" ] || continue
files_found=true
break
done
# Only proceed if files are found
if [ "$files_found" = false ]; then
exit 0
fi
for f in "$SOURCE_DIR"/*
do
[ -f "$f" ] || continue
filename=$(basename "$f")
name="${filename%.*}"
output_file="$OUTPUT_DIR/$name.mp4"
# Skip if already compressed
if [ -f "$output_file" ]; then
echo "⏭️ Skipping $filename (already compressed)"
continue
fi
echo "βŒ› Waiting for $filename to finish copying..."
# Wait for file to be fully copied
while :
do
size1=$(stat -f%z "$f")
sleep 5
size2=$(stat -f%z "$f")
[ "$size1" -eq "$size2" ] && break
done
echo "πŸš€ Compressing: $filename"
# Retry logic
attempts=0
max_attempts=3
# Ensure HandBrake CLI exists
if [ ! -f "/opt/homebrew/bin/HandBrakeCLI" ]; then
echo "❌ HandBrakeCLI not found at /opt/homebrew/bin/HandBrakeCLI"
echo "$f" >> "$LOG_FILE"
continue
fi
until /opt/homebrew/bin/HandBrakeCLI -i "$f" -o "$output_file" -e x264 -q 20 -B 160 -w 3840 -l 2160 --rate 60 --pfr -O --optimize || [ $attempts -ge $max_attempts ]
do
attempts=$((attempts + 1))
echo "πŸ” Retry $attempts for $filename"
sleep 10
done
if [ $attempts -ge $max_attempts ]; then
echo "❌ FAILED: $filename β€” logged to $LOG_FILE"
echo "$f" >> "$LOG_FILE"
else
echo "βœ… Success: $output_file"
echo "πŸ“¦ Moving original to archive"
mv "$f" "$PROCESSED_DIR/"
fi
done
echo "🏁 All done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment