6

I was looking for the best way to find iterate over files in a variables path and came across this question.

However, this and every other solution I've found uses a literal path rather than a variable, and I believe this is my problem.

for file in "${path}/*"
do
     echo "INFO - Checking $file"
     [[ -e "$file" ]] || continue
done

Even though there are definitely files in the directory (and if i put one of the literal paths in place of ${path} I get the expected result), this always only iterates once, and the value of $file is always the literal value of ${path}/* without any globbing.

What am I doing wrong?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Jordan Mackie
  • 2,264
  • 4
  • 25
  • 45

1 Answers1

10

Glob expansion doesn't happen inside quotes (both single and double) in shell.

You should be using this code:

for file in "$path"/*; do
     echo "INFO - Checking $file"
     [[ -e $file ]] || continue
done
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    See [this thread](https://unix.stackexchange.com/questions/239772/bash-iterate-file-list-except-when-empty) for more tips on how to handle an empty directory when iterating with globs. – Antonin Décimo Jun 29 '21 at 09:52