Test whether a glob has any matches in bash

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

    I like

    exists() {
        [ -e "$1" ]
    }
    
    if exists glob*; then
        echo found
    else
        echo not found
    fi
    

    This is both readable and efficient (unless there are a huge number of files).
    The main drawback is that it's much more subtle than it looks, and I sometimes feel compelled to add a long comment.
    If there's a match, "glob*" is expanded by the shell and all the matches are passed to exists(), which checks the first one and ignores the rest.
    If there's no match, "glob*" is passed to exists() and found not to exist there either.

    Edit: there may be a false positive, see comment

提交回复
热议问题