我有一个名为 diff.txt 的文件。 想检查它是否为空。我做过类似的工作,但无法正常工作。
if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
拼写错误令人恼火,不是吗? 检查一下 "empty "的拼写,然后再试试这个:
#!/bin/bash -e
if [ -s diff.txt ]
then
rm -f empty.txt
touch full.txt
else
rm -f full.txt
touch empty.txt
fi
我很喜欢 shell 脚本,但它的一个缺点是,当你拼写错误时,shell 无法帮助你,而像 C++ 编译器这样的编译器却可以帮助你。
顺便注意一下,我按照 @Matthias 的建议,把 empty.txt
和 full.txt
的角色对调了一下。
[ -s file.name ] || echo "file is empty"
[[ -s file ]]]--> 检查文件大小是否大于 0
if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi
如果需要,它会检查当前目录下的所有 *.txt 文件,并报告所有空文件:
for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done