Test whether a glob has any matches in bash

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

    In Bash, you can glob to an array; if the glob didn't match, your array will contain a single entry that doesn't correspond to an existing file:

    #!/bin/bash
    
    shellglob='*.sh'
    
    scripts=($shellglob)
    
    if [ -e "${scripts[0]}" ]
    then stat "${scripts[@]}"
    fi
    

    Note: if you have nullglob set, scripts will be an empty array, and you should test with [ "${scripts[*]}" ] or with [ "${#scripts[*]}" != 0 ] instead. If you're writing a library that must work with or without nullglob, you'll want

    if [ "${scripts[*]}" ] && [ -e "${scripts[0]}" ]
    

    An advantage of this approach is that you then have the list of files you want to work with, rather than having to repeat the glob operation.

提交回复
热议问题