Test whether a glob has any matches in bash

后端 未结 19 2698
夕颜
夕颜 2020-11-22 15:51

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

19条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 16:49

    Bash specific solution:

    compgen -G ""
    

    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.

    UPDATE: Example usage requested.

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

提交回复
热议问题