Example of a shell script that scans a given directory, finds any PNG images, and optimizes them using a tool called optipng. This is a mid-level use case which combines several concepts like loops, conditionals, functions, and using external commands.
Shell script:
#!/bin/bash
# Function that optimizes PNG images
optimize_image() {
file="$1"
echo "Optimizing $file..."
optipng -o7 "$file"
}
# Check if optipng is installed
if ! command -v optipng &> /dev/null
then
echo "optipng could not be found, please install it first."
exit
fi
# Check if a directory has been provided
if [ $# -eq 0 ]
then
echo "Please provide a directory."
exit 1
fi
DIR="$1"
# Check if the provided directory exists
if [ ! -d "$DIR" ]
then
echo "The directory $DIR does not exist."
exit 1
fi
# Loop over all PNG files in the directory
find "$DIR" -name "*.png" -type f | while read -r file
do
optimize_image "$file"
done
echo "Optimization complete."
In this script, the optimize_image function optimizes a single image with optipng. It’s called for every PNG file in the directory you provide when running the script. The script also checks if optipng is installed and if the provided directory exists.
optipng is a command-line utility used to optimize PNG (Portable Network Graphics) files to a smaller size without losing any information. The optimization process involves various compression algorithms and strategies to minimize the file size while maintaining the same visual quality.
The basic usage of optipng is quite simple. You just need to provide the name of the PNG file you want to optimize:
optipng image.png
This will replace image.png with its optimized version.
optipng has several options you can use to customize the optimization process. For example, you can set the optimization level with the -o option. The levels range from 0 (least optimization, fastest) to 7 (most optimization, slowest). For example:
optipng -o7 image.png
The -o7 option tells optipng to use the highest level of optimization, even though it might take more time.
One important thing to note is that optipng does lossless compression, which means that the quality of the image will not be degraded. The optimization involves removing unnecessary metadata, choosing the most efficient PNG encoding, and applying gzip compression.
You can install optipng in many Linux distributions with the package manager. For example, on Ubuntu, you can use apt:
sudo apt-get install optipng
Other urls to refer