【问题标题】:Always gives false even though file exists and is not empty即使文件存在且不为空,也总是给出 false
【发布时间】:2015-07-16 20:11:33
【问题描述】:

我有一个 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,它都会给我错误的值。我什至可以输入一个根本不存在的文件;它仍然会给我错误的价值。这是为什么呢?

【问题讨论】:

  • &&后面需要一个空格
  • 这是我的编辑错误,我已修复。但是这个解决方案不起作用。
  • -f 测试文件是否存在,但您在“不存在”部分得到了它
  • 你认为[ -f "$file" ] && [ -s "$file" ] 会做什么?
  • 如果您在运行此程序时使用set -xbash -x yourscript,您会看到它运行[ -f '' ][ -s '' ],这会给您一个线索,然后再在这里询问file未正确设置(由于 read $file 中的 $)。

标签: bash


【解决方案1】:

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

文件存在且大小大于零

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

你的输出也被切换了,所以当文件存在时它输出does not exists,因为如果文件存在并且-s将给出TRUE并且有一个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

【讨论】:

  • -s 在dir 的情况下返回true。如果我们只想检查没有空文件,那么结合 -f 和 -s 条件
【解决方案2】:

请注意,如果文件存在且不为空,[ -f "$file" ] && [ -s "$file" ] 将返回 true

其他选项:

if [[ -f "/path/to/file" && -s "/path/to/file" ]]; then 
    echo "exist and not empty"
else 
    echo "not exist or empty"; 
fi

【讨论】:

  • 另一个选项[ -f "$file" -a -s "$file" ]
  • Shellcheck 实际上对此发出警告:Prefer [ p ] && [ q ] as [ p -a q ] is not well defined.
【解决方案3】:

这是真正的解决方案:

if [[ -f $file && -s $file ]]

[[ 不需要引号,因为[[ 可以更直观地处理空字符串和带有空格的字符串。

向您提出的解决方案:

if [ -s "$file" ]

是错误的,因为它相当于:

if [[ -e $file && -s $file ]]

除了由单词 -f 指示的常规文件之外,它还查找:

  1. 目录
  2. 符号链接
  3. 阻止特殊设备
  4. 字符设备
  5. Unix 套接字(本地域套接字)
  6. 命名管道

【讨论】:

  • [ 是 shell,[[ 是 bash(shell 是最小的终端解释器,bash 是高级解释器)
猜你喜欢
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 2012-09-04
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
相关资源
最近更新 更多