Skip to content

Instantly share code, notes, and snippets.

@icalrn
Created December 8, 2021 02:47
Show Gist options
  • Save icalrn/79a9b4fe5056a17f92c0619d3932faf0 to your computer and use it in GitHub Desktop.
Save icalrn/79a9b4fe5056a17f92c0619d3932faf0 to your computer and use it in GitHub Desktop.
Optimize Images with Imagemin while Preserving Directory Structure
#!/bin/sh
find ./public/images -type f \( -iname \*.jpg -o -iname \*.png -o -iname \*.svg \) | xargs -I % sh -c 'imagemin % -o $(dirname % | sed --expression="s/public/&\/optimized/")'
# `find` - Look for files in the specified path
# -type f - Filter the files to only include regular files
# \( \) - Group statements so that the previous flag (-type f) applies to all following statements
# -iname - Look for files with specified names, case insensitive
# -o - OR operand
#
# xargs - Build and execute command
# -I % - Replace occurences of % with names read from stdin
# sh -c - Executes the following command string with sh
# imagemin % - Executes imagemin to optimize image, % being replaced by xargs with names from the find part of the command
# -o - Designate the output directory
# dirname % - Trims the last part of the file path so that only the directory path remains
# sed - Execute string transformation with following parameters
# --expression="s/public/&\/optimized/" - Look for string 'publi' and append it with '/optimized'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment