如何在 Bash 中检查文件是否为空? [英] How to check if a file is empty in Bash?
问题描述
我有一个名为 diff.txt 的文件.我想检查它是否为空.
I have a file called diff.txt. I Want to check whether it is empty.
我写了一个类似下面的 bash 脚本,但我无法让它工作.
I wrote a bash script something like below, but I couldn't get it work.
if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
推荐答案
拼写错误很烦人,不是吗?检查 empty
的拼写,然后试试这个:
Misspellings are irritating, aren't they? Check your spelling of empty
, but then also try this:
#!/bin/bash -e
if [ -s diff.txt ]; then
# The file is not-empty.
rm -f empty.txt
touch full.txt
else
# The file is empty.
rm -f full.txt
touch empty.txt
fi
我非常喜欢 shell 脚本,但它的一个缺点是当你拼错时 shell 无法帮助你,而像你的 C++ 编译器这样的编译器可以帮助你.
I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.
顺便说一下,正如@Matthias 建议的那样,我已经交换了 empty.txt
和 full.txt
的角色.
Notice incidentally that I have swapped the roles of empty.txt
and full.txt
, as @Matthias suggests.
这篇关于如何在 Bash 中检查文件是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!