简体   繁体   English

Bash shell 不识别 else 语句

[英]Bash shell don't recognize else statement

I am trying to build a script that asks the user to enter the file size and path, if the file size is bigger then the limit the file should bd delete, the problem is even if the file is smaller then the entered value, the script delete that file anyway, I think there is an error in my Else statement我正在尝试构建一个脚本,要求用户输入文件大小和路径,如果文件大小大于文件应该删除的限制,问题是即使文件小于输入的值,脚本无论如何删除该文件,我认为我的 Else 语句中有错误

and I already tried " https://www.shellcheck.net/ " and give me this error and I didn't know how to solve it if [ "$SIZE" -gt "$limit" ]; ^-- SC2154: limit is referenced but not assigned.而且我已经尝试过“ https://www.shellcheck.net/ ”并给了我这个错误, if [ "$SIZE" -gt "$limit" ]; ^-- SC2154: limit is referenced but not assigned.我不知道如何解决它if [ "$SIZE" -gt "$limit" ]; ^-- SC2154: limit is referenced but not assigned.

#!/bin/bash
 limit="$1"
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

Edit: I removed 'read' and now I get this error '[: -gt: unary operator expected ' and even if the file size is bigger then the entered value its go directly to else statement编辑:我删除了“读取”,现在我得到了这个错误“[:-gt:一元运算符预期”,即使文件大小大于输入的值,它的 go 直接到 else 语句

ShellCheck is on the right track: limit is indeed not being assigned, because your read statement is invalid. ShellCheck 走在正确的轨道上:确实没有分配limit ,因为您的read语句无效。 Your script therefore always thinks limit=0 and therefore that all files should be deleted.因此,您的脚本始终认为limit=0 ,因此应该删除所有文件。

Instead of代替

read -i limit="$1"

you should just do你应该这样做

limit="$1"

Here is the complete script with this change:以下是此更改的完整脚本:

#!/bin/bash
limit=$1
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

And here's an example of running it:这是一个运行它的例子:

$ 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM