13

The following bash snippet works great when there are actually *.txt files in the directory.

for txt in *.txt
do                                               
  echo "loading data from $txt"
done   

When there aren't, the literal *.txt falls into the loop as $txt (not good).

How do I change this code so that when there are no *.txt files, the do ... done block is skipped?

kfmfe04
  • 865
  • 1
  • 9
  • 21

2 Answers2

17

Put this magic incantation before the for statement:

shopt -s nullglob

(documentation)

Cristian Ciupitu
  • 5,513
  • 2
  • 37
  • 47
kfmfe04
  • 865
  • 1
  • 9
  • 21
6

The nullglob option (@kfmfe04's answer) is best if you are using bash (not a brand-X shell), and don't have to worry about nullglob changing/breaking anything else. Otherwise, you can use this (slightly messier) option:

for txt in *.txt
do
  [ -e "$txt" ] || continue
  echo "loading data from $txt"
done

This silently skips files that don't exist (mainly "*.txt" if there were no matches, but possibly also files that were deleted between when the for generated the list and when the loop got to them...)

Gordon Davisson
  • 34,084
  • 5
  • 66
  • 70