Test whether a glob has any matches in bash

后端 未结 19 2697
夕颜
夕颜 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:57

    This abomination seems to work:

    #!/usr/bin/env bash
    shopt -s nullglob
    if [ "`echo *py`" != "" ]; then
        echo "Glob matched"
    else
        echo "Glob did not match"
    fi
    

    It probably requires bash, not sh.

    This works because the nullglob option causes the glob to evaluate to an empty string if there are no matches. Thus any non-empty output from the echo command indicates that the glob matched something.

提交回复
热议问题