我有一个脚本,每次从 FTP 服务器下载 17 个文件,但有时由于某些原因,某些文件的权重为“0”。
所以我正在寻找一个 bash 脚本来检查是否有大小为零的文件。
我怎么能这样做?
编辑:我想使用 if-else 语句:如果有任何 0 字节文件,我将不得不再次运行 bash 脚本。
如果只想列出 0 字节文件,可以使用find:
使用示例find:
$ find . -type f -size 0b
./4.txt
./5.txt
./6.txt
Run Code Online (Sandbox Code Playgroud)
使用的好处find是您可以轻松地通过管道将其用于xargs对文件执行您想要的操作(例如删除它们),这比使用for循环要容易得多。
如果您想在找到这些文件后对其进行处理,例如,删除所有 0 字节文件(同时考虑奇怪的文件名),我会执行以下操作:
$ find -type f -size 0b -print0 | xargs -0I file rm -v file
removed ‘./4.txt’
removed ‘./5.txt’
removed ‘./6.txt’
Run Code Online (Sandbox Code Playgroud)
此外,另一个选项可以简单地以人类可读的格式列出目录中的所有文件以及文件大小,使用du -h.
使用示例du:
$ du -h *
1.0K 1.txt
1.0K 2.txt
1.0K 3.txt
0 4.txt
0 5.txt
0 6.txt
Run Code Online (Sandbox Code Playgroud)
编辑: 只要您知道如何查找空文件,就可以通过多种方式执行其他操作。以下示例可能不是执行此操作的最佳方式,但如果您绝对要查找if/else语句,则可以执行以下操作:
#!/bin/bash
for i in *; do
if [[ $(du -h "$i" | awk '{print $1}') = 0 ]]; then
echo "$i is empty."
else
echo "$i is not empty."
fi
done
Run Code Online (Sandbox Code Playgroud)
返回:
1.txt is not empty.
2.txt is not empty.
3.txt is not empty.
4.txt is empty.
5.txt is empty.
6.txt is empty.
Run Code Online (Sandbox Code Playgroud)