Bash check if file exists with double bracket test and wildcards

后端 未结 2 733
轮回少年
轮回少年 2020-12-19 00:53

I am writing a Bash script and need to check to see if a file exists that looks like *.$1.*.ext I can do this really easily with POSIX test as [ -f *.$1.*

2条回答
  •  情书的邮戳
    2020-12-19 01:31

    as your question is bash tagged, you can take advantage of bash specific facilities, such as an array:

    file=(*.ext)
    [[ -f "$file" ]] && echo "yes, ${#file[@]} matching files"
    

    this first populates an array with one item for each matching file name, then tests the first item only: Referring to the array by name without specifying an index addresses its first element. As this represents only one single file, -f behaves nicely.

    An added bonus is that the number of populated array items corresponds with the number of matching files, should you need the file count, and can thereby be determined easily, as shown in the echoed output above. You may find it an advantage that no extra function needs to be defined.

提交回复
热议问题