我创建了一个脚本来在我的 CentOS 7 服务器上运行自动备份。备份存储到 /home/backup 目录。该脚本有效,但现在我想合并一种在备份发生后计算文件数的方法,如果数量超过 5,则删除最旧的备份。
以下是我的备份脚本。
#!/bin/bash
#mysqldump variables
FILE=/home/backup/databasebk_!`date +"Y-%m-%d_%H:%M"`.sql
DATABASE=database
USER=root
PASS=my password
#backup command process
mysqldump --opt --user=${USER} --password=${PASS} ${DATABASE} > ${FILE}
#zipping the backup file
gzip $FILE
#send message to the user with the results
echo "${FILE}.gz was created:"
ls -l ${FILE}.gz
# This is where I would like to count the number of files
# in the directory and if there are more than 5 I would like
# to delete the oldest …Run Code Online (Sandbox Code Playgroud) 如果解析 的输出ls很危险,因为它可能会中断一些时髦的字符(空格、\n、 ... ),那么了解目录中文件数量的最佳方法是什么?
我通常依靠find避免这种解析,但同样地,find mydir | wc -l由于相同的原因会中断。
我现在正在 Solaris 上工作,但我正在寻找一个在不同的 unice 和不同的 shell 中尽可能可移植的答案。
如果我这样做ls -1 target_dir | wc -l,我会得到一个目录中的文件数。我觉得这有点麻烦。有没有更优雅或更简洁的方式?
我有一个 shell 脚本,用于find -print0将要处理的文件列表保存到临时文件中。作为日志记录的一部分,我想输出找到的文件数,因此我需要一种方法来获得该计数。如果该-print0选项没有被用于安全,我可以用它wc -l来计算。
我需要计算文件夹下的文件数并使用以下命令。
cd testfolder
bash-4.1$ ls | wc -l
6
Run Code Online (Sandbox Code Playgroud)
其实这个文件夹下只有五个文件,
bash-4.1$ ls
total 44
-rw-r--r-- 1 comp 11595 Sep 4 22:51 30.xls.txt
-rw-r--r-- 1 comp 14492 Sep 4 22:51 A.pdf.txt
-rw-r--r-- 1 comp 8160 Sep 4 22:51 comparison.docx.txt
-rw-r--r-- 1 comp 903 Sep 4 22:51 Survey.pdf.txt
-rw-r--r-- 1 comp 1206 Sep 4 22:51 Steam Table.xls.txt
Run Code Online (Sandbox Code Playgroud)
看起来ls | wc -l甚至将其total 44视为文件,这是不正确的。
我想知道特定目录中的项目数(文件、子目录等)。
似乎有很多关于它的问题,但大多数(如果不是全部)答案似乎都依赖于wc -l. 例如:
ls -1 | wc -l
但是,如果一个或多个文件的名称中有新行,这将给出错误的答案。这里的另一个问题是ls -1可能返回的不仅仅是文件。
一个不可移植的答案隐藏在数千个类似问题之一的评论中。有效,但不幸的是它依赖-printf于我的发行版中不可用的。
find -maxdepth 1 -type f -printf "\n" | wc -l
(by Godlygeek)
是否有更便携的解决方案可以正确处理名称中包含任何字符的文件?
我想获取目录及其子目录中所有文件的计数,但我不希望它计数 .zip 文件。所以我想是这样的:
find . -iname "*.zip" -type f 2> /dev/null | wc -l
Run Code Online (Sandbox Code Playgroud)
除了向后 - 只会返回 .zip 文件,而且我只想计算其他文件。
files ×3
command-line ×2
linux ×2
ls ×2
shell ×2
shell-script ×2
bash ×1
directory ×1
filesystems ×1
posix ×1
ubuntu ×1
variable ×1
wc ×1
wildcards ×1