如何在 Bash 中检查文件是否为空?

新手上路,请多包涵

我有一个名为 diff.txt 的文件。我想检查它是否为空。

我写了一个类似下面的 bash 脚本,但我无法让它工作。

 if [ -s diff.txt ]
then
        touch empty.txt
        rm full.txt
else
        touch full.txt
        rm emtpy.txt
fi

原文由 Mich 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 734
2 个回答

拼写错误很烦人,不是吗?检查您的拼写 empty ,但也试试这个:

 #!/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++ 编译器这样的编译器可以帮助你。

请注意,正如@Matthias 所建议的那样,我已经交换了 empty.txtfull.txt 的角色。

原文由 thb 发布,翻译遵循 CC BY-SA 4.0 许可协议

[ -s file.name ] || echo "file is empty"

原文由 mickey white 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题