gpt4 book ai didi

linux - Bash shell 无法识别 else 语句

转载 作者:行者123 更新时间:2023-12-04 19:31:49 27 4
gpt4 key购买 nike

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

我已经尝试了“https://www.shellcheck.net/”并给了我这个错误,我不知道如何解决它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

编辑:我删除了“读取”,现在我得到了这个错误“[:-gt:一元运算符预期”
即使文件大小大于输入的值,它也会直接转到 else 语句

最佳答案

ShellCheck 在正确的轨道上:limit确实没有被分配,因为你的 read声明无效。因此,您的脚本总是认为 limit=0因此应该删除所有文件。

代替

read -i limit="$1"

你应该这样做
limit="$1"

以下是此更改的完整脚本:
#!/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

这是一个运行它的例子:
$ 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

关于linux - Bash shell 无法识别 else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61900975/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com