I want to resize all PNG files in ~/somefolder/ whose filenames are NOT started with tn_ to 50% of its original size and rename the output file with a tn_ as its prefix and its original name. I know there's a convert command and I've already installed it. I guess it can be done via bash and some magic but I am quite new to Unix. I am using Mac OSX.

What should I do?


Here is one way (put it in a file and execute it with any POSIX shell like bash or ksh):

cd ~/somefolder/ || exit 1
for f in *.png
  case $f in
  (tn_*) continue ;;
  (*) convert "${f}" -resize 50%x50% "tn_${f}" ;;

With modern shells the case construct could also be replaced by a terser conditional command:

cd ~/somefolder/ || exit 1
for f in *.png
    [[ "$f" != tn_* ]] && convert "${f}" -resize 50%x50% "tn_${f}"

(But this code is from memory and untested, so inspect the convert command about the actual resize-syntax, and try it in some sample directory on a few sample files first.)

  • Thanks. What is the || exit 1 for? – AGamePlayer Mar 30 '15 at 5:01
  • 1
    A safety measure that let's the script exit (without doing anything) if the directory can't be entered. If that code would not be there it would start doing the subsequent operations in your current working directory, which may be undesired. – Janis Mar 30 '15 at 5:05
  • Nice use of case! (Though I personally would be worried about spaces in filenames and write case "$f" in just to be sure, regardless of whether it's needed there.) – Ulrich Schwarz Mar 30 '15 at 5:24
  • @Ulrich, FYI: The case construct has the "advantage" that it runs also in old Bourne shell, while the second version (the test operator with regexps) would not. WRT the variable quoting; they are indeed not necessary in the case argument (and also not even in the [[...]] construct; but in the latter test construct I deliberately added them because some folks may use the old [...] test command, and there they would be necessary). – Janis Mar 30 '15 at 7:03

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.