Bash shell 无法识别 else 语句

Bash shell don't recognize else statement

我正在尝试构建一个脚本,要求用户输入文件大小和路径,如果文件大小大于限制文件应该 bd 删除,问题是即使文件小于输入的值,脚本无论如何都会删除该文件,我认为我的 Else 语句中有错误

而且我已经尝试过“https://www.shellcheck.net/”并给我这个错误,我不知道如何解决它 if [ "$SIZE" -gt "$limit" ]; ^-- SC2154: limit is referenced but not assigned.

#!/bin/bash
 limit=""
shift 1 
for file in "$@"; do
SIZE="$(stat --format="%s" "$file")"
if [ "$SIZE" -gt "$limit" ];
then
echo "$file is $SIZE bytes. Deleting..; -rm $file"
 else 
echo "file is smaller then limit no delete"
 fi
 done

编辑:我删除了 'read',现在我收到此错误“[: -gt: unary operator expected” 即使文件大小大于输入的值,它也会直接转到 else 语句

ShellCheck 走上正轨:limit 确实没有被赋值,因为你的 read 声明无效。因此,您的脚本始终认为 limit=0,因此应删除所有文件。

而不是

read -i limit=""

你应该这样做

limit=""

这是包含此更改的完整脚本:

#!/bin/bash
limit=
shift 1
for file in "$@"; do
SIZE="$(stat --format="%s" "$file")"
if [ "$SIZE" -gt "$limit" ];
then
echo "$file is $SIZE bytes. Deleting..; -rm $file"
 else
echo "file is smaller then limit no delete"
 fi
 done

这里有一个 运行 的例子:

$ ls -l big small
-rw-r--r-- 1 me me 505 May 19 15:01 big
-rw-r--r-- 1 me me 495 May 19 15:01 small

$ ./myscript 500 big small
big is 505 bytes. Deleting..; -rm big
file is smaller then limit no delete