1

I'm writing a bash script to do something if the directory has files of extensions: jpg, jpeg or png. But I'm screwing up when I try to check this with the for or while loops.

while [ filename in $IMAGE_DIR/*.jp*g -o filename in $IMAGE_DIR/*.png ] ; do
        # do something here

But I receive compile error:

line 30: [: too many arguments

I tried the following loops to no avail.

for (filename in $IMAGE_DIR/*.jp*g) || (filename in $IMAGE_DIR/*.png); do
while [ filename in $IMAGE_DIR/*.jp*g ] || [ filename in $IMAGE_DIR/*.png ] ; do
while [[ filename in $IMAGE_DIR/*.jp*g ]] || [[ filename in $IMAGE_DIR/*.png ]] ; do
while [[ filename in $IMAGE_DIR/*.jp*g ] || [ filename in $IMAGE_DIR/*.png ]] ; do
while (( filename in $IMAGE_DIR/*.jp*g )) || (( filename in $IMAGE_DIR/*.png )) ; do
while ( filename in $IMAGE_DIR/*.jp*g )) || (( filename in $IMAGE_DIR/*.png ) ; do

What am I missing here?

cappy0704
  • 557
  • 2
  • 9
  • 30
  • 1
    Why don't you `do_something *.jpg *.jpeg *.png` if there aren't any, you will do_nothing. Or use `find -name "*.jpeg"` or any other pattern you want for their name, and `xargs` them to your job. There is no reason to check all the filenames around, the shell offers you these files with one command or one glob. – thanasisp Sep 25 '20 at 16:14
  • You want to `do something if the directory has files of extensions` or do you want to _iterate_ over these files? If this a duplicate of https://stackoverflow.com/questions/6363441/check-if-a-file-exists-with-wildcard-in-shell-script ? – KamilCuk Sep 25 '20 at 17:16
  • @KamilCuk: just want to iterate over these files. – cappy0704 Sep 25 '20 at 18:50

2 Answers2

3

Here is the way I believe it's easier to iterate multiple "types|extensions" of files. I hope with that you have an idea how to continue, you can create your if conditions inside that for loop.

$ ls -l
-rw-rw-r--  1 lucas lucas    0 Sep 25 13:58  test.jpeg
-rw-rw-r--  1 lucas lucas    0 Sep 25 13:58  test.jpg
-rw-rw-r--  1 lucas lucas    0 Sep 25 13:58  test.png
-rwxrwxr-x  1 lucas lucas   62 Sep 25 13:59  test.sh

$ cat test.sh 
#!/bin/bash
for i in *.jpg *jpeg *.png; do
  echo "hi $i"
done

$ ./test.sh 
hi test.jpg
hi test.jpeg
hi test.png
lucasgrvarela
  • 351
  • 1
  • 4
  • 9
1

You are use readarray Instead of ".txt" just put any extension you want.

readarray FILES <<< "$(find . -name "*.txt")";
for file in ${FILES[@]}; do
    echo $file
done  
slowbone
  • 11
  • 2
  • Isn't that just a more complicated way of writing `for file in *.txt`? It also descends into subdirectories, which may or may not be desired. – Benjamin W. Sep 25 '20 at 17:09