【问题标题】:Bash shell don't recognize else statementBash shell 无法识别 else 语句
【发布时间】:2020-09-06 02:29:40
【问题描述】:

我正在尝试构建一个脚本,要求用户输入文件大小和路径,如果文件大小大于文件应该删除的限制,问题是即使文件小于输入的值,脚本还是删除了那个文件,我认为我的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 语句

【问题讨论】:

  • read -i limit="$1" 应该做什么?你如何调用你的脚本?
  • read 用于从终端输入设置变量,$1 用于访问命令行参数。
  • 现在我收到此错误 [: -gt: unary operator expected 并且即使文件大小大于输入的值,它也会直接转到 else 语句

标签: linux centos centos7 redhat


【解决方案1】:

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

【讨论】:

  • 现在我收到此错误 [: -gt: unary operator expected 并且即使文件大小大于输入的值,它也会直接转到 else 语句 -
  • 我已经发布了包含此更改的完整脚本,以及显示两个分支的运行示例。你能试试同样的方法吗?
  • 如果您使用if [ $SIZE -gt $limit ](不带双引号),则会出现错误[: -gt: unary operator expected。如果变量被正确引用,则不应该出现。
  • 现在完成了,我的错误是双引号
猜你喜欢
  • 1970-01-01
  • 2018-03-23
  • 2023-04-04
  • 2019-10-22
  • 2015-07-05
  • 1970-01-01
  • 2021-08-19
  • 2017-09-05
  • 2020-02-15
相关资源
最近更新 更多