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

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

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


当前回答

#!/usr/bin/env bash

# If it is set, then an unmatched glob is swept away entirely -- 
# replaced with a set of zero words -- 
# instead of remaining in place as a single word.
shopt -s nullglob

M=(*px)

if [ "${#M[*]}" -ge 1 ]; then
    echo "${#M[*]} matches."
else
    echo "No such files."
fi

其他回答

#!/usr/bin/env bash

# If it is set, then an unmatched glob is swept away entirely -- 
# replaced with a set of zero words -- 
# instead of remaining in place as a single word.
shopt -s nullglob

M=(*px)

if [ "${#M[*]}" -ge 1 ]; then
    echo "${#M[*]} matches."
else
    echo "No such files."
fi
[ `ls glob* 2>/dev/null | head -n 1` ] && echo true

ls | grep - q“glob *。”

这不是最有效的解决方案(如果目录中有大量文件,它可能会比较慢),但它很简单,易于阅读,而且它的优点是正则表达式比普通的Bash glob模式更强大。

如果你想在遍历这些文件之前测试它们是否存在,你可以使用这个模式:

  for F in glob*; do
    if [[ ! -f $F ]]; then break; fi
    
    ...

  done

如果glob不匹配任何内容,$F将是未展开的glob(在本例中为'glob*'),如果同名文件不存在,则跳过循环的剩余部分。

在Bash中是这样的(测试文件包含模式):

shopt -s nullglob
compgen -W *pattern* &>/dev/null
case $? in
    0) echo "only one file match" ;;
    1) echo "more than one file match" ;;
    2) echo "no file match" ;;
esac

它比compgen -G好得多:因为我们可以区分更多的情况,更精确。

它只能使用一个通配符*。