我如何使用带通配符参数的test
命令来检查任意数量的文件?
例如:
test -f /var/log/apache2/access.log.* && echo "exists one or more files"
目前,它打印出
error: bash: test: too many arguments
我如何使用带通配符参数的test
命令来检查任意数量的文件?
例如:
test -f /var/log/apache2/access.log.* && echo "exists one or more files"
目前,它打印出
error: bash: test: too many arguments
这个解决方案对我来说更直观:
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,而不是正则表达式。请参见Confusion with shell-globbing wildcards and Regex获取更多信息。
首先,将文件存储在目录中并以数组形式呈现:
logfiles=(/var/log/apache2/access.log.*)
然后对数组的计数进行测试:
if [[ ${#logfiles[@]} -gt 0 ]]; then
echo 'At least one file found'
fi
['/var/log/apache2/access.log.*']
(包含“*”的一个元素)。
建议:[[ ${#logfiles[@]} -gt 1 || -e ${logfiles[0] ]]
或者简单地使用 [[ -e ${logfiles[0] ]]
(就像dmaticzka所做的那样)。 - simoheshopt -s nullglob
以避免如果没有文件存在,则在数组内容中有一个元素。在这种情况下,变量将为空,并且后续测试更容易进行。 - zero0coolif [[ ${#logfiles[@]} -gt 0 ]] && [[ -f ${#logfiles[@]} ]] ; then
。对于晚来的派对,抱歉,那么shopt -s nullglob
就不必要了吗? - sunta3iouxosif [[ ${#logfiles[@]} -gt 0 ]] && [[ -e ${logfiles[@]} ]]; then
来捕捉到 0 个文件的情况!或者使用 -f
或 -d
来仅测试文件/目录 ;)。 - skupjoelogfiles =(/ var / log / apache2 / access.log.*)
将始终包含至少一个未展开的通配符,因此可以简单地测试第一个元素是否存在:logfiles=(/var/log/apache2/access.log.*)
if [[ -f ${logfiles[0]} ]]
then
echo 'At least one file found'
else
echo 'No file found'
fi
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
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."
或者使用 find
if [ $(find /var/log/apache2/ -type f -name "access.log.*" | wc -l) -gt 0 ]; then
echo "ok"
else
echo "ko"
fi
find /var/log/apache2/ -maxdepth 1 -type f -name "access.log.*" -print -quit
(在第一个匹配后退出)。 - simoheif [[ $(ls -1 /var/log/apache2/access.log.* | wc -l ) -gt 0 ]] 2> /dev/null
if [[ $(ls -1 /var/log/apache2/access.log.* | wc -l ) -gt 0 ]] 2> /dev/null
then
echo "exists one or more files."
fi