我怎样才能对任意数量的文件使用test命令,通过regexp在参数中传递
例如:
test -f /var/log/apache2/access.log.* && echo "exists one or more files"
Run Code Online (Sandbox Code Playgroud)
但是割印错误:bash:test:参数太多了
小智 29
这个解决方案在我看来更直观:
if [ `ls -1 /var/log/apache2/access.log.* 2>/dev/null | wc -l ` -gt 0 ];
then
echo "ok"
else
echo "ko"
fi
Run Code Online (Sandbox Code Playgroud)
小智 9
首先,将目录中的文件存储为数组:
logfiles=(/var/log/apache2/access.log.*)
Run Code Online (Sandbox Code Playgroud)
然后对数组的计数进行测试:
if [[ ${#logfiles[@]} -gt 0 ]]; then
echo 'At least one file found'
fi
Run Code Online (Sandbox Code Playgroud)
为避免“参数过多错误”,您需要 xargs。不幸的是,test -f不支持多个文件。以下单行应该工作:
for i in /var/log/apache2/access.log.*; do test -f "$i" && echo "exists one or more files" && break; done
Run Code Online (Sandbox Code Playgroud)
顺便说一句,/var/log/apache2/access.log.*被称为 shell-globbing,而不是 regexp,请检查这个:Confusion with shell-globbing wildcards and Regex。
小智 6
这个适合与Unofficial Bash Strict Mode一起使用,当没有找到文件时, no 具有非零退出状态。
该数组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
Run Code Online (Sandbox Code Playgroud)
如果您希望批量处理文件列表,而不是对每个文件执行单独的操作,您可以使用 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
Run Code Online (Sandbox Code Playgroud)