for breaks script execution in ZSH

3

1

I feel dumb. I have a ZSH script with eg two file loops, eg:

for f (*aaa*) {echo "$f"}
for f (*bbb*) {echo "$f"}

The script exits if the first find does not find matching files. I need the script to keep working.

What am I missing?

Igor Spasic

Posted 2014-08-21T21:29:07.557

Reputation: 199

Answers

5

If there is no match for *aaa* an error is reported by default. This is what causes your script to exit.

To avoid this the NULL_GLOB option has to be set. Then instead of reporting an error the pattern is simply removed from the argument list, if nothing matches.

There are several ways to set NULL_GLOB:

  • for the whole script by passing the -G command line option to zsh. This can also be done on the hash-bang line:
$ zsh -G SCRIPT
#!/usr/bin/zsh -G
for f (*aaa*) {echo "$f"}
for f (*bbb*) {echo "$f"}
  • for all following lines by setting it with setopt:
setopt NULL_GLOB
for f (*aaa*) {echo "$f"}
for f (*bbb*) {echo "$f"}
  • for a single pattern by using the glob qualifier N:
for f (*aaa*(N)) {echo "$f"}
for f (*bbb*) {echo "$f"}

Adaephon

Posted 2014-08-21T21:29:07.557

Reputation: 3 864

and I thought I know something about zsh... wow! this answer is great :) – rsm – 2014-08-21T23:02:11.970