20

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
  • 1,025

2 Answers2

21

Put this magic incantation before the for statement:

shopt -s nullglob

(documentation)

kfmfe04
  • 1,025
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...)