23

我如何对任意数量的文件使用测试命令,通过正则表达式传入参数

例如:

test -f /var/log/apache2/access.log.* && echo "exists one or more files"

但割打印错误:bash:测试:参数太多

4

10 回答 10

45

这个解决方案在我看来更直观:

if [ `ls -1 /var/log/apache2/access.log.* 2>/dev/null | wc -l ` -gt 0 ];
then
    echo "ok"
else
    echo "ko"
fi
于 2014-08-05T13:52:25.130 回答
7

为避免“参数过多错误”,您需要 xargs。不幸的是,test -f不支持多个文件。以下单行应该工作:

for i in /var/log/apache2/access.log.*; do test -f "$i" && echo "exists one or more files" && break; done

顺便说一句,/var/log/apache2/access.log.*称为 shell-globbing,而不是 regexp,请检查:Confusion with shell-globbing wildcards and Regex

于 2013-02-08T04:27:46.333 回答
5

First, store files in the directory as an array:

logfiles=(/var/log/apache2/access.log.*)

Then perform a test on the count of the array:

if [[ ${#logfiles[@]} -gt 0 ]]; then
  echo 'At least one file found'
fi
于 2018-03-02T20:55:07.267 回答
4

如果您希望将文件列表作为批处理进行处理,而不是对每个文件执行单独的操作,您可以使用 find,将结果存储在变量中,然后检查变量是否不为空。例如,我使用以下代码编译源目录中的所有 .java 文件。

SRC=`find src -name "*.java"`
if [ ! -z $SRC ]; then
    javac -classpath $CLASSPATH -d obj $SRC
    # stop if compilation fails
    if [ $? != 0 ]; then exit; fi
fi
于 2014-04-25T18:24:35.147 回答
4

这个适用于Unofficial Bash Strict Mode,没有找到文件时没有非零退出状态。

该数组logfiles=(/var/log/apache2/access.log.*)将始终至少包含未扩展的 glob,因此可以简单地测试第一个元素的存在:

logfiles=(/var/log/apache2/access.log.*)

if [[ -f ${logfiles[0]} ]]
then 
  echo 'At least one file found'
else
  echo 'No file found'
fi
于 2018-06-27T12:22:01.820 回答
1

您只需要测试是否ls有要列出的内容:

ls /var/log/apache2/access.log.* >/dev/null 2>&1 && echo "exists one or more files"
于 2015-07-18T08:11:22.830 回答
1

主题变奏:

if ls /var/log/apache2/access.log.* >/dev/null 2>&1
then 
  echo 'At least one file found'
else
  echo 'No file found'
fi
于 2017-03-23T10:24:49.627 回答
0
ls -1 /var/log/apache2/access.log.* | grep . && echo "One or more files exist."
于 2014-10-17T10:59:32.663 回答
0

更简单:

if ls /var/log/apache2/access.log.* 2>/dev/null 1>&2; then
   echo "ok"
else
   echo "ko"
fi
于 2020-05-04T12:43:49.467 回答
0

或使用查找

if [ $(find /var/log/apache2/ -type f -name "access.log.*" | wc -l) -gt 0 ]; then
  echo "ok"
else
  echo "ko"
fi
于 2018-05-17T13:05:53.250 回答