4

I am currently trying to write a bash script which helps me step through a directory and check for .jpeg or .jpg extensions on files. I've come up with the following:

#declare $PICPATH, etc...

for file in $PICPATH
    if [ ${file -5} == ".jpeg" -o ${file -4} == ".jpg" ];
    then
        #do some exif related stuff here.
    else
        #throw some errors
    fi
done

Upon execution, bash keeps throwing a an error on the if line: "syntax error near unexpected token `if'.

I'm a completely new to scripting; what is wrong with my if statement?

Thanks.

1
  • To remove the last 5 characters of a variable use ${file::-5}, what you are doing ${file -5} won't work. Commented Oct 9, 2019 at 12:31

2 Answers 2

12

I think you're just missing the do clause of the for loop:

#declare $PICPATH, etc...

for file in $PICPATH; do
    if [ ${file -5} == ".jpeg" -o ${file -4} == ".jpg" ];
    then
        #do some exif related stuff here.
    else
        #throw some errors
    fi
done
Sign up to request clarification or add additional context in comments.

2 Comments

I can't believe I missed that. I spent an hour trying to figure out what went wrong. Thanks a lot.
You can put the do on a new line if you prefer it. Then, you can omit the semicolon ; before it. The same applies to the then after the if.
2
${file -5}

is a syntax error. Maybe you mean

${file#*.}

?

Anyway, better do :

for file in $PICPATH; do
    image_type="$(file -i "$file" | awk '{print gensub(";", "", $2)}')"
    case $image_type in
        image/jpeg)
            # do something with jpg "$file"
        ;;
        image/png)
            # do something with png "$file"
        ;;
        *)
            echo >&2 "not implemented $image_type type "
            exit 1
        ;;
    esac
done

If you only want to treat jpg files, do :

for file in $PICPATH; do
    image_type="$(file -i "$file" | awk '{print gensub(";", "", $2)}')"
    if [[ $image_type == image/jpeg ]]; then
            # do something with jpg "$file"
    fi
done

1 Comment

Thanks a lot for the improved version, but I only need the case for jpeg: everything else should be ignored. Thanks a lot for the response anyways.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.