2

I'd like to create a bash script to resize images up to 800px keeping proportion...

My code doesn't work in bash, but it works using identify with a single image :

#!/bin/bash
for file in ./**/public/uploads/*.*; do
  width = $(identify -format "%w" ${file})
  if [ width > 800 ]
  then
    echo $file // resize image
  fi
done
exit 0;

Issue : I get Permission denied on line 3

I tried the solution given in one of the answers below:

#!/bin/bash
shopt -s globstar
for file in ./**/public/uploads/*.*; do 
  width=$(identify -format "%w" "${file}")
  if [ "$width" -gt 800 ]
  then
    echo "$file"
  fi
done
exit 0;

And I now get this error message:

identify.im6: Image corrupted   ./folder/public/uploads/ffe92053ca8c61835aa5bc47371fd3e4.jpg @ error/gif.c/PingGIFImage/952.
./images.sh: line 6: width: command not   found
./images.sh: line 7: [integer expression expected
  • 1
    When asking about scripts that "don't work", you need to tell us i) what you expect to happen; ii) what actually happens iii) the exact error you receive. That said, I'm guessing you forgot to add shopt globstar to your script to enable the **. – terdon Jul 27 '16 at 14:33
2

I see two obvious issues in your script. First, the ** is provided by the globstar option which isn't on by default. You've probably activated it in your interactive shell, but you need to do so for the script as well.

Then, you'e not actually comparing $width but the string width. The $ is needed in [ ].

The last issue is that some of the files you are running this on are either corrupted, or not images. In any case, the identify command fails on them so $width is empty. A simple solution would be to test whether $width is empty (-z "$width") and only compare if it is not (! -z "$width"):

Try this instead:

#!/bin/bash
shopt -s globstar
for file in ./**/public/uploads/*.*; do 
  width=$(identify -format "%w" "${file}")
  if [[ ! -z "$width" && "$width" -gt 800 ]]
  then
    echo "$file"
  fi
done
exit 0;
1

The problem (or, at least, one of the problems) is that you're saying

width = $(identify -format "%w" "${file}")

You need to eliminate the spaces before and after the =, like this:

width=$(identify -format "%w" "${file}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.