# Directory to process (default is current directory) DIR="."
# Check if a directory is provided as an argument if [ $# -eq 1 ]; then DIR="$1" fi
# Check if the directory exists if [ ! -d "$DIR" ]; then echo"Error: Directory '$DIR' does not exist." exit 1 fi
# Change to the specified directory cd"$DIR" || exit 1
# Create a temporary directory for intermediate files TEMP_DIR=$(mktemp -d) if [ ! -d "$TEMP_DIR" ]; then echo"Error: Could not create temporary directory." exit 1 fi
# Counter for renaming count=1
# Find all image files, sort them by name, and rename # Using ls without -t for alphabetical sorting for file in $(ls *.{jpg,jpeg,png,JPG,JPEG,PNG} 2>/dev/null); do # Skip if not a regular file if [ ! -f "$file" ]; then continue fi
# Generate new filename new_name="$count.jpg"
# Move to temp directory first to avoid overwriting mv"$file""$TEMP_DIR/$new_name" || { echo"Error: Failed to move $file to temp directory." exit 1 }
# Increment counter ((count++)) done
# Move files back from temp directory to original directory mv"$TEMP_DIR"/* . 2>/dev/null if [ $? -ne 0 ]; then echo"Warning: Some files may not have been moved back." fi
# Clean up temp directory rmdir"$TEMP_DIR"
# Check if any files were renamed if [ $count -eq 1 ]; then echo"No image files found in '$DIR'." else echo"Renamed $((count-1)) image files in '$DIR'." fi