bashglob

Test whether a glob has any matches in Bash


If I want to check for the existence of a single file, I can test for it using test -e filename or [ -e filename ].

Supposing I have a glob and I want to know whether any files exist whose names match the glob. The glob can match 0 files (in which case I need to do nothing), or it can match 1 or more files (in which case I need to do something). How can I test whether a glob has any matches? (I don't care how many matches there are, and it would be best if I could do this with one if statement and no loops (simply because I find that most readable).

(test -e glob* fails if the glob matches more than one file.)


Solution

  • Bash-specific solution:

    compgen -G "<glob-pattern>"
    

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

    Exit status is:

    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