Check whether a certain file type/extension exists in directory

前端 未结 15 1584
时光取名叫无心
时光取名叫无心 2021-01-30 06:12

How would you go about telling whether files of a specific extension are present in a directory, with bash?

Something like

if [ -e *.flac ]; then 
echo t         


        
15条回答
  •  鱼传尺愫
    2021-01-30 06:48

    Here is a solution using no external commands (i.e. no ls), but a shell function instead. Tested in bash:

    shopt -s nullglob
    function have_any() {
        [ $# -gt 0 ]
    }
    
    if have_any ./*.flac; then
        echo true
    fi
    

    The function have_any uses $# to count its arguments, and [ $# -gt 0 ] then tests whether there is at least one argument. The use of ./*.flac instead of just *.flac in the call to have_any is to avoid problems caused by files with names like --help.

提交回复
热议问题