linux - 检查bash上是否只有一个文件存在当前数据

标签 linux bash shell for-loop if-statement

如何检查当前日期是否只有一个文件。 我有一个脚本:

name="nginx.log"
data=$(date +%Y.%m.%d)
current_nginx=$name.$data
cd /var/log/
for i in `ls "$name"*`; do
if [[ $i == "$current_nginx" ]]; then
    echo "only one file is exists"
else
    echo "other files is exists"
fi
done

我有文件:

ls -l /var/log/nginx.log*
-rw-r--r-- 1 root root  4814275 May 12 23:59 /var/log/nginx.log.2017.05.12.gz
-rw-r--r-- 1 root root 40468077 May 13 09:40 /var/log/nginx.log.2017.05.13

在脚本的结果中我有:

bash test.sh
other files is exists
only one file is exists

哪里有错误。我重复。如果我只有一个带有当前日期的 nging.log,我想得到“只有一个文件存在”。如果我有更多 nginx.log.* 文件,我想收到消息“其他文件存在”。

最佳答案

for i in `ls "$name"*`; 

如果与该 glob 匹配的(任何)条目是目录,这也会列出它们的内容。如果它们不是,或者您不想列出它们的内容,只需使用 for i in "$name"* ; —— 无论如何,扩展 glob 的是 shell,而 ls 在这里没有做任何有用的事情。

您可以在 Bash 中计算与 glob 匹配的文件数量:

shopt -s nullglob
files=( "$name"* )
count=${#files[@]}              # take the count
for f in "${files[@]}" ; do     # or loop over them
    ...

关于linux - 检查bash上是否只有一个文件存在当前数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43950288/

相关文章:

linux - 如何在 Bash 中逐行打印时对数据进行排序

linux - Grepping 不适合特定给定字符集的字符

linux - 将单列文本文件编辑为多列

javascript - 如何使用Coffeescript和shellJS编写可执行的shell脚本?

java - 如何打开终端窗口并在 php 中执行命令?

php - IMAP 已安装但无法工作?

bash - 使用 bash 4 语法将 Makefile 中字符串的首字母大写

linux - 我如何使用 cli 列出所有带有特定标签的 S3 存储桶?

MySQL 用空格连接列

shell - Bash-如果再声明,该如何表达