Test whether a glob has any matches in Bash

Bash-specific solution:

compgen -G "<glob-pattern>"

Escape the pattern or it’ll get pre-expanded into matches.

Exit status is:

  • 1 for no-match,
  • 0 for ‘one or more matches’

stdout is a list of files matching the glob.
I think this is the best option in terms of conciseness and minimizing potential side effects.

Example:

if compgen -G "/tmp/someFiles*" > /dev/null; then
    echo "Some files exist."
fi

Leave a Comment