Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
1  
if [ "*.txt" != '*.txt' ] ; then do loop here ; fi –  ott-- Dec 14 '12 at 14:08
    
@ott-- +1 for offering an alternative solution –  kfmfe04 Dec 14 '12 at 14:36
1  
@ott: [ "*.txt" != '*.txt' ] is always false -- both strings are in quotes, so neither gets checked for matches. If you remove the quotes from one it ... has other problems. –  Gordon Davisson Dec 14 '12 at 19:47
    
@GordonDavisson +1 for pointing this out: shell scripting seems to be full of surprises... –  kfmfe04 Dec 14 '12 at 20:05
1  
@GordonDavisson Indeed, it must be done in 2 steps to work: files=$(echo *.txt) and then: if [ "${files}" != '*.txt' ] ; then. –  ott-- Dec 15 '12 at 14:17

2 Answers 2

Looks like google had the answer to this one.

Put this magic incantation before the for statement:

shopt -s nullglob
share|improve this answer

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...)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.