Linux Terminal

BASh script to convert WebP images to jpg

For the past couple of years it feels like websites use Google’s WebP image format more and more. Images stored in this format are not yet well supported in file browsers and image viewers, so I needed a method to batch convert them. I wrote a simple script to batch convert all WebP images in the current directory to the much more common and widely supported JPEG image format, so I can easily preview them in my file browser and share them directly with friends. The script depends on ImageMagick’s convert utility for the actual file conversion. I simply run it every now and then or when I need to find an image I just downloaded.


for f in ./*.webp; do
	if [ -f "$f" ]; then
	    if [ ! -f "$newfilename" ] ; then
		    printf "Converting %s to %s " "$f" "$newfilename"
		    convert "$f" "$newfilename"
		    if [ -f "$newfilename" ]; then
			rm $f
			printf "...... Done!! \n"
		    printf "\n !!!File $s already exists !!!\n" $newfilename
exit 0

Code breakdown

The script is not at all sophisticated and does the most basic of checks.

The whole script is inside a loop that goes through all files in the current directory with a .webp extension.

If the file exists (line 4) and is a “regular” file (i.e. not a directory, socket or link) the loop continues.

The part of the filename before the last dot (hopefully that’s the base filename without the extension) is assigned to variable basefilename (line 5) and the filename for the converted file is created and stored in variable newfilename (line 6).

A check is done (line 7) to see if a file with the name of the final file already exists. In that case further processing is skipped, a message is printed (line 15) and the loop jumps to the next iteration (file).

If the final file doesn’t exist a message is printed (line 8) and ImageMagick’s convert utility is called to do the actual conversion (line 9).

Line 10 simply checks that the new file has been created and the original file is then deleted (line 11).

If the check fails (new file doesn’t exist) the loop simply continues without any warnings or errors.

Possible Enhancements

Stuff I may add in the future if I don’t get too lazy. If you’re new to shell scripting (like me) you can try to do these on your own.

  • Add parameter to enable processing of directories specified in the arguments instead of the current one. (-d ?)
  • Add parameter to specify output directory instead of current one. (-o ?)
  • Add parameter to enable recursive processing of files in subdirectories inside the current/specified one (-r ?)
  • Add parameter to keep the source files (-k ?) [maybe make this behaviour default as it’s safer]
  • Add warning message when output file isn’t created

One comment

  1. Thx for the code – was a direct drop in for a down and dirty I was working on, appreciate it!

Comments are closed.