nikksan
nikksan

Reputation: 3481

Git Bash for loop through files

Okay, I am trying to loop through all images in a directory and do some compression on them. Here is my code.

#!/bin/bash
for f in *.jpeg; do 
    echo "Processing $f file..";
    magick convert -quality 85% $f $f
done

And here is the output from it:

 $ bash compress.sh Processing *.jpeg file.. convert: unable to open
 image '*.jpeg': Invalid argument @ error/blob.c/OpenBlob/3094.
 convert: no images defined `*.jpeg' @
 error/convert.c/ConvertImageCommand/3254.

The $f reference is actually the string "*.jpeg", which is definitely not correct.

Here is my folder structure.

folder structure

Upvotes: 2

Views: 9829

Answers (2)

SergA
SergA

Reputation: 1174

You should lookup files with appropriate filename mask (directory and extension). Also there should be skip path if bash can't expand filename:

#!/bin/bash

IMAGE_PATH=`dirname ${BASH_SOURCE[0]}`/nature
for f in $IMAGE_PATH/*.jpg $IMAGE_PATH/*.jpeg; do 
  echo -n "Processing $f file... ";
  if [ ! -r "$f" ]; then
    echo "skip!";
    continue;
  fi;
  magick convert -quality 85% "$f" "$f";
  echo "done.";
done

PS: "$f" (with quotes) used for files with spaces in their names.

UPDATE: Add using script directory.

Upvotes: 1

nikksan
nikksan

Reputation: 3481

I ended up doing this, which does the job.

#!/bin/bash
find ./images -name '*.jpg' | while read FILE; do
    magick convert -quality 75% "$FILE" "$FILE"    
done

Upvotes: 1

Related Questions