Reputation: 1134
$ for f in /etc/shell*; do echo $f; done
/etc/shells
$
good!
$ for f in /etc/no_such*; do echo $f; done
/etc/no_such*
$
BAD!
How can I reap off wildcard evaluation if no files present?
Upvotes: 4
Views: 409
Reputation: 74685
There is a specific shell option to enable this behaviour with globs, called nullglob
. To enable it, use shopt -s nullglob
.
When this option is enabled, a pattern with no matches evaluates to nothing, rather than to itself.
This is non-standard feature provided by bash, so if you're using another shell or are looking for a more widely compatible option you can add a condition to the loop body:
for f in /etc/no_such*; do [ -e "$f" ] && echo "$f"; done
This will only echo if the file exists.
Upvotes: 6