You are immediately removing your output file after creating it. You also have issues with quoting in the bash -c
script's command substitution around sed
, and there are a few instances of variables not being quoted at all.
Corrected variant:
find "$@" -type f \( -iname '*.jpg' -o -iname '*.jpeg' \) -exec bash -c '
for pathname do
cwebp -quiet -q 90 -o "${pathname%.*}.webp" -- "$pathname" &&
rm -f -- "$pathname"
done' bash {} +
This makes the operation more efficient by calling bash -c
with batches of found files instead of once per file.
The original file is not removed unless cwebp
exited successfully. The .webp
filename suffix replaces the original filename suffix by means of a standard parameter substitution, rather than by using sed
. Note that -r
is not needed with rm
when removing files.
The script now also support taking multiple directories on the command line.
Without using find
, in bash
:
shopt -s nullglob dotglob nocaseglob
shopt -s globstar
for dirpath do
for pathname in "$dirpath"/*/.{jpg,jpeg}; do
[ ! -f "$pathname" ] && continue
cwebp -quiet -q 90 -o "${pathname%.*}.webp" -- "$pathname" &&
rm -f -- "$pathname"
done
done
The only difference is that this bash
loop would also process symbolic links to regular files matching the patterns. If that is an issue, then change the -f
test in the inner loop to
if [ ! -f "$pathname" ] || [ -h "$pathname" ]; then
continue
done
cwebp
does, but if it's writing to$webp_path
, then you are immediately removing that afterwards. You could also get rid ofsed
withwebp_path=${0%.*}.webp
. – Kusalananda Jan 12 '22 at 11:11rm -rf
may remove a lot. Even if the original author wanted to remove the file just created, I wonder why they used-r
. – Kamil Maciorowski Jan 12 '22 at 11:17'
aftersed
closes the'
after-exec bash -c
! – Marcus Müller Jan 12 '22 at 11:21