Test whether a glob has any matches in bash

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

    #!/usr/bin/env bash
    
    # If it is set, then an unmatched glob is swept away entirely -- 
    # replaced with a set of zero words -- 
    # instead of remaining in place as a single word.
    shopt -s nullglob
    
    M=(*px)
    
    if [ "${#M[*]}" -ge 1 ]; then
        echo "${#M[*]} matches."
    else
        echo "No such files."
    fi
    

提交回复
热议问题