-
-
Save kojiromike/2e5ea9f0aad7f6ae303b to your computer and use it in GitHub Desktop.
Fix name of images in Magento whose names only vary by case (renaming them both in the filesystem and the database catalog). This is useful if media files need to pass through a case-insensitive filesystem, like a Mac.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Settings | |
SUFFIX=alt | |
MAGERUNCMD=magerun | |
# Sanity Checks | |
type $MAGERUNCMD >/dev/null 2>&1 || { | |
echo "ERROR: This script requires the command '$MAGERUNCMD' to be executable in the current path." | |
exit | |
} | |
[[ "$PWD" == *media/catalog/product ]] || { | |
echo "ERROR: This script should be run from the 'media/catalog/product' directory of your Magento install." | |
exit | |
} | |
# Directions | |
echo "It is highly recommended that you run the 'media:images:removeorphans' magerun extension before this." | |
echo '---' | |
if [ ! "$1" = '-f' ]; then | |
echo 'This script performs a dry run by default. To force changes pass flag -f.' | |
read -p "Press [Enter] key to continue with dry run or [Ctrl-C] to exit..." | |
else | |
echo 'WARNING: Forcing updates. Changes are destructive and cannot be undone.' | |
read -p "Press [Enter] key to continue with force mode or [Ctrl-C] to exit..." | |
fi | |
echo '---' | |
# Work Time | |
DUPLICATES=$(find . -type f) | |
echo "$DUPLICATES" | sort -f | uniq -id | while read -r FILENAME; do | |
INDEX=1 | |
while read OLD_FILENAME; do | |
NEW_FILENAME=$(echo "$OLD_FILENAME" | tr '[:upper:]' '[:lower:]' | perl -pe "s/\.([^.]*)\$/_$SUFFIX$INDEX.\1/") | |
if [ ! -e "$NEW_FILENAME" ]; then | |
eval $MAGERUNCMD db:query $([ ! "$1" = '-f' ] && printf -- --only-command) \ | |
"UPDATE mag_catalog_product_entity_media_gallery SET value = '${NEW_FILENAME#.}' WHERE BINARY value = '${OLD_FILENAME#.}';" \ | |
&& eval $([ ! "$1" = '-f' ] && printf echo) mv "$OLD_FILENAME" "$NEW_FILENAME" | |
else | |
echo "New name $NEW_FILENAME for $OLD_FILENAME already exists. Refusing to move or update DB." | |
false | |
fi | |
if [ $? -gt 0 ]; then | |
echo 'Terminating early on fatal error.' | |
[ "$1" = '-f' ] && echo 'Error above may need to be manually fixed.' | |
exit | |
fi | |
((INDEX++)) | |
done < <(grep -i "$FILENAME" <<< "$DUPLICATES") | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment