我如何对任意数量的文件使用测试命令,通过正则表达式传入参数
例如:
test -f /var/log/apache2/access.log.* && echo "exists one or more files"
但割打印错误:bash:测试:参数太多
我如何对任意数量的文件使用测试命令,通过正则表达式传入参数
例如:
test -f /var/log/apache2/access.log.* && echo "exists one or more files"
但割打印错误:bash:测试:参数太多
这个解决方案在我看来更直观:
if [ `ls -1 /var/log/apache2/access.log.* 2>/dev/null | wc -l ` -gt 0 ];
then
echo "ok"
else
echo "ko"
fi
为避免“参数过多错误”,您需要 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。
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
如果您希望将文件列表作为批处理进行处理,而不是对每个文件执行单独的操作,您可以使用 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
这个适用于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
您只需要测试是否ls
有要列出的内容:
ls /var/log/apache2/access.log.* >/dev/null 2>&1 && echo "exists one or more files"
主题变奏:
if ls /var/log/apache2/access.log.* >/dev/null 2>&1
then
echo 'At least one file found'
else
echo 'No file found'
fi
ls -1 /var/log/apache2/access.log.* | grep . && echo "One or more files exist."
更简单:
if ls /var/log/apache2/access.log.* 2>/dev/null 1>&2; then
echo "ok"
else
echo "ko"
fi
或使用查找
if [ $(find /var/log/apache2/ -type f -name "access.log.*" | wc -l) -gt 0 ]; then
echo "ok"
else
echo "ko"
fi