bash - 即使文件存在且不为空,也总是给出 false

我有一个 bash 脚本:

echo " enter file name "
read $file
if [ -f "$file" ] && [ -s "$file" ]
then 
   echo " file does not exist, or is empty "
else
   echo " file exists and is not empty "
fi

无论我作为 $file 输入什么,它都会给我错误值。我什至可以输入一个根本不存在的文件;它仍然会给我错误的值(value)。这是为什么呢?

最佳答案

检查-s就足够了,因为它说:

FILE exists and has a size greater than zero

http://unixhelp.ed.ac.uk/CGI/man-cgi?test

你的输出也被切换,所以当文件存在时输出 does not exists,因为如果文件存在 -s 将给出 TRUE AND 有一个 size > 0

你应该正确地使用:

echo " enter file name "
read file
if [ -s "$file" ]
then 
   echo " file exists and is not empty "
else
   echo " file does not exist, or is empty "
fi

这将为您提供预期的输出。

应该也是

read file

而不是

read $file

如果您想了解更多信息,我建议您阅读 man testman read

https://stackoverflow.com/questions/30080997/

相关文章:

linux - 检查 VT-x 是否已激活而无需在 Linux 中重新启动?

xml - CHMOD 755 与 750 权限集之间的差异

linux - 是否可以在 XTerm 或 Konsole 中使 stdout 和 stderr 输

linux - 获取 Docker 容器名称

linux - 在 Bash 中从最后到第一个输出文件行

linux - 没有换行的cat文件

linux - 如何在 unix 中解压 tar.bz 文件?

linux - 内联 if shell 脚本

linux - Unix管道到ls

Linux 上的 C++ 开发 - 我从哪里开始?