Check whether a certain file type/extension exists

2019-03-08 22:54发布

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 true; 
fi 

标签: linux bash shell
13条回答
时光不老,我们不散
2楼-- · 2019-03-08 23:33

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.

查看更多
登录 后发表回答