简体   繁体   中英

Bash scripting: Checking multiple file conditions in loop

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?

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

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM