[Bash] Beginner at scripting

Hi, I'm a beginner at shell scripting, just started scripting in bash a few days ago.

I want to test if the command ls *.jpg returns exit code 2, and if yes I want to execute a new command ls *.jpeg, doing a test on it... and pretty much repeat the procedure.

Is this correct?

#!/bin/bash

url=$1
category=$2

wget $1 

filename=$(ls *.jpg)
if test $? -eq 2; then
        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/_thumb/$category
        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/$category
        mogrify -resize 160x140 /var/www/blogger/gallery/_thumb/"$category"/$filename
        rm /var/www/blogger/scripts/*.jpg
        else filename=$(ls *.jpeg)
                if test $? -eq 2; then
                        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/_thumb/$category
                        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/$category
                        mogrify -resize 160x140 /var/www/blogger/gallery/_thumb/"$category"/$filename
                        rm /var/www/blogger/scripts/*.jpeg
                        else filename=$(ls *.png)
                                if test $? -eq 2; then
                                        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/_thumb/$category
                                        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/$category
                                        mogrify -resize 160x140 /var/www/blogger/gallery/_thumb/"$category"/$filename
                                        rm /var/www/blogger/scripts/*.png
                                fi
                fi      
fi

Not quite sure what is going on here, but there is a lot of duplication of code and the following should be functionally equilivent, without the duplicated code.

It's quite normal to use the "[" construct instead of test and tends to make things a little more readable.

#!/bin/bash
 
url=$1
category=$2
 
wget $1
 
for ext in jpg jpeg png
do
    filename=$(ls *.$ext)
    if [ $? -eq 2 ]; then
        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/_thumb/$category
        cp /var/www/blogger/scripts/$filename /var/www/blogger/gallery/$category
        mogrify -resize 160x140 /var/www/blogger/gallery/_thumb/"$category"/$filename
        rm /var/www/blogger/scripts/*.$ext
        break
    fi
done

Note if you dont wan't the error from ls to go to stderr you can redirect this to null like:

filename=$(ls *.$ext 2> /dev/null)