0

I am iterating over a set of files with:

for F in *.note.*; do echo "File is $F"; done

If five files match I might get the following output:

File is a_dispatch.note.23-MAY-16
File is b_dispatch.note.25-MAY-16
File is x_dispatch.note.25-MAY-16
File is y_dispatch.note.25-MAY-16
File is z_dispatch.note.25-MAY-16

However when no files are matched, e.g. by running:

for F in *.nomatch.*; do echo "File is $F"; done

I get:

File is *.nomatch.*

Now, if no files match I clearly don't want to take any action. Where I am simply doing an echo of the filename in this example I might have significant processing which won't want to be executed when there are no files.

What am I missing here? Why am I getting the loop executed when no files matched?

user2567544
  • 376
  • 1
  • 12
  • Please search before posting. See [this question](http://unix.stackexchange.com/questions/84826/looping-over-a-folder-enter-anyways-the-loop) on *Unix and Linux*. – trojanfoe May 26 '16 at 10:25
  • 1
    place `shopt -s nullglob` before your loop – anubhava May 26 '16 at 10:25

1 Answers1

0
for F in *.note.*; do test -f  $F && echo "File is $F"; done

Break down :

    for F in *.note.*;
    do
        test -f  $F
        if [ "$?" -eq 0 ];then

        echo "File is $F";
        fi
    done
P....
  • 17,421
  • 2
  • 32
  • 52