shopt -s nullglob

Hi,

I am using BASH. In a directory there are files that match either of the following 2 patterns: [AST]*.L1A_[GL]AC* or S*.L1A_MLAC*

I would like to write a script that will include a for loop, where for each file in the directory, a certain function will be performed. For example:

for FILE in [AST]*.L1A_[GL]AC* S*.L1A_MLAC*; do
echo $FILE
done

The content of the directory will be random, and there are 3 potential scenarios: 1) Files of both patterns exist in the directory, 2) Only files of the 1st pattern exist, 3) Only files of the 2nd pattern exist. The last two scenarios are problematic as one of the patterns won't be matched, resulting in my script behaving oddly.

  • I believe the way around this is to use the shopt -s nullglob option. Does anyone have any other ideas?

  • MAIN QUESTION: Where in the code should I put the shopt -s nullglob and shopt -u nullglob? Of course the shopt -s nullglob should be set immediately before the the beginning of the for loop. But, can the shopt -u nullglob be immediately after the beginning of the for loop (ie):

shopt -s nullglob
for FILE in [AST]*.L1A_[GL]AC* S*.L1A_MLAC*; do
shopt -u nullglob
echo $FILE
done

OR after the conclusion of the for loop (ie):

shopt -s nullglob
for FILE in [AST]*.L1A_[GL]AC* S*.L1A_MLAC*; do
echo $FILE
done
shopt -u nullglob

The reason I ask is because I will of course have more complicated code within the for loop, and only want the shopt nullglob command to affect the pattern matching when calling the for loop.

Thanks for your help.

Mike

The first option should be fine. The list that the for loop will iterate through is only evaluated once, so turning it off in the first invocation of the do ... done part should be safe.

I didn't know about nullglob, thanks for the handy tip!

As shopt -s nullglob is not standard, I'd use a test inside the loop:

for FILE in [AST]*.L1A_[GL]AC* S*.L1A_MLAC*; do
   [ -f "$FILE" ] || continue
   echo "$FILE"
   : ....
done

Hi cfajohnson,

  • I appreciate the response. Could you please expand on your statement that shopt -s nullglob is not standard? What do you mean exactly?

  • Also, is the purpose of the code that you have written inside the for loop to eliminate the error message that occurs when one of the patterns is not matched?

Thanks for your help!

Mike

It only works in bash.

Exactly. It acheives the same effect as shopt -s nullglob, but will work in all Bourne-type shells.