使用 test -e 检查目录中是否存在文件

问题描述 投票:0回答:1

如果给定文件存在,我想执行特定的代码块。

if ssh user@$host "test -e $file";
...

$file
是完整的文件名时,例如
/tmp/test1.txt
,效果很好。但是,如果我想检查目录中是否存在 any 文件,例如
$file
/tmp/*
,我得到

bash: test: too many arguments

是否可以将

*
test -e
一起使用,如果可以,如何使用?

bash
1个回答
0
投票

我发现的最简单的方法是使用 count 命令来计算与提供的路径匹配的文件/文件夹。从手册页:

示例

count $PATH

返回用户 PATH 变量中的目录数。

根据我的测试,当没有任何内容与提供的路径匹配时,甚至会返回状态 1(错误)。所以你可以这样做:

# Note: The number output of count is not important
#       because we can simply use the returned status code.
if ssh user@$host "count /tmp/* > /dev/null"; then
  echo "Temp file exists in host."
else
  echo "No temp file found."
fi

注意:使用 GNU bash 5.2.26 对主机进行测试,它可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.