脚本错误:-le:需要二元运算符

Roc*_*645 2 bash scripts

我刚刚开始编写 shell 脚本,尝试执行以下脚本时出错:

我在script.sh文件中有以下脚本

echo “enter a value”
read n
s=0
i=0
while [ $i –le $n ]
do
  if [ `expr $i%2` -eq 0 ]
  then
    s= `expr $s + $i `
  fi
  i= `expr $i + 1`
done
echo “sum of n even numbers”
echo $s
Run Code Online (Sandbox Code Playgroud)

脚本输出:

akhil@akhil-Inspiron-5559:~/Desktop/temp$ chmod 755 script.sh
akhil@akhil-Inspiron-5559:~/Desktop/temp$ ./script.sh
“enter a value”
3
./script.sh: line 5: [: –le: binary operator expected
“sum of n even numbers”
0
Run Code Online (Sandbox Code Playgroud)

我得到的错误的根源是什么?

Yar*_*ron 9

错误的来源:[: –le: binary operator expected是您使用的是unicode版本而不是常规版本-

注意:同样适用于unicode 您正在使用的而不是常规的"

我已将您的代码重新格式化为如下所示:

#!/bin/bash
echo "enter a value"
read -r n
s=0
i=0
while [ $i -le "$n" ]
  do
  if [ "$(expr $i%2)" -eq 0 ]
  then
    s=$(expr $s + $i)
  fi
  i=$(expr $i + 1)
done
echo "sum of n even numbers"
echo "$s"
Run Code Online (Sandbox Code Playgroud)

我做了以下更改:

  • 替换了unicode您使用的字符版本
  • 添加 #!/bin/bash
  • 标志space后删除=
  • 一些额外的改进。