如果我想检查单个文件是否存在,我可以使用test -e filename或[-e filename]进行测试。

假设我有一个glob,我想知道是否有文件名与glob匹配的文件存在。glob可以匹配0个文件(在这种情况下,我不需要做任何事情),也可以匹配1个或多个文件(在这种情况下,我需要做一些事情)。我如何测试一个glob是否有任何匹配?(我不在乎有多少匹配,这将是最好的,如果我能做到这一点与一个if语句和没有循环(只是因为我发现最易读)。

(如果glob匹配多个文件,则test -e glob*失败。)


当前回答

我喜欢

exists() {
    [ -e "$1" ]
}

if exists glob*; then
    echo found
else
    echo not found
fi

这既可读又有效(除非有大量的文件)。 主要的缺点是它比看起来要微妙得多,有时我觉得有必要添加一个很长的评论。 如果有匹配项,shell将展开“glob*”,并将所有匹配项传递给exists(),后者检查第一个匹配项并忽略其余匹配项。 如果没有匹配,则将"glob*"传递给exists()并发现它也不存在。

编辑:可能是假阳性,见评论

其他回答

if ls -d $glob > /dev/null 2>&1; then
  echo Found.
else
  echo Not found.
fi

请注意,如果有很多匹配或文件访问缓慢,这可能会非常耗时。

根据miku的想法,简化一下他的回答:

M=(*py)
if [ -e ${M[0]} ]; then
  echo Found
else
  echo Not Found
fi

在Bash中,你可以glob到数组;如果glob不匹配,你的数组将包含一个与现有文件不对应的条目:

#!/bin/bash

shellglob='*.sh'

scripts=($shellglob)

if [ -e "${scripts[0]}" ]
then stat "${scripts[@]}"
fi

注意:如果你设置了nullglob, scripts将是一个空数组,你应该使用["${scripts[*]}"]或["${#scripts[*]}" != 0]来测试。如果您正在编写一个必须使用或不使用nullglob的库,那么您将需要

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

这种方法的一个优点是,这样您就有了想要处理的文件列表,而不必重复glob操作。

#!/bin/bash
set nullglob
touch /tmp/foo1 /tmp/foo2 /tmp/foo3
FOUND=0
for FILE in /tmp/foo*
do
    FOUND=$((${FOUND} + 1))
done
if [ ${FOUND} -gt 0 ]; then
    echo "I found ${FOUND} matches"
else
    echo "No matches found"
fi

nullglob和compgen都只在一些bash shell上有用。

在大多数shell上工作的(非递归)解决方案是:

set -- ./glob*                  # or /path/dir/glob*
[ -f "$1" ] || shift            # remove the glob if present.
if    [ "$#" -lt 1 ]
then  echo "at least one file found"
fi