首页 > 解决方案 > 在子文件夹中批量转换图像文件 jpg、png 到 webp

问题描述

我找到了一个脚本来转换目录中的文件,但我需要子目录

你能帮助我吗 ?

#!/bin/bash

PATH=/usr/local/bin:/usr/bin:/bin

# cd to the directory of the image so we can work with just filenames
dir="$(dirname "$1")"
cd "$dir" || exit 1
base="$(basename "$1" .png)"

# create a WebP version of the PNG
cwebp -q 80 "$base".png -o "$base".webp

# delete the WebP file if it is equal size or larger than the original PNG
if [[ `stat -c '%s' "$base".webp` -ge `stat -c '%s' "$base".png` ]]; then
    echo "Deleting WebP file that is no smaller than PNG"
    rm -f "$base".webp
fi

# delete the WebP file if it is size 0
if [[ -f "$base".webp && ! -s "$base".webp ]]; then
    echo "Deleting empty WebP file"
    rm -f "$base".webp
fi

标签: linuxbashimagewebp

解决方案


好消息:您不必更改脚本!

您可以通过以下命令找到根目录中的所有目录:

find /path/to/root/dir -type d 

您可以为每个找到的目录添加一些命令的执行:

假设您的脚本名称是script.sh并且它位于您的主目录中,并且您希望在当前目录下的所有子目录上运行它(包括当前目录):

find . -type d -exec ~/script.sh "{}" \;

推荐阅读