Test whether a glob has any matches in bash

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

    set -- glob*
    if [ -f "$1" ]; then
      echo "It matched"
    fi
    

    Explanation

    When there isn't a match for glob*, then $1 will contain 'glob*'. The test -f "$1" won't be true because the glob* file doesn't exist.

    Why this is better than alternatives

    This works with sh and derivates: ksh and bash. It doesn't create any sub-shell. $(..) and `...` commands create a sub-shell; they fork a process, and therefore are slower than this solution.

提交回复
热议问题