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

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

我刚刚开始编写 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

脚本输出:

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

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

答案1

错误的根源:[: –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"

我做了以下更改:

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

答案2

Yaron 的回答可以帮助您理解并消除语法错误。

我的答案使用一些“更好”的语法来做同样的事情和其他事情,这可能就是你想要的。

#!/bin/bash

read -p "enter a number: " n

s=0
i=1
j=0
while [ $i -le $n ]
do
  if [ $(( i % 2 )) -eq 0 ]
  then
    s=$(( s + i ))
    j=$(( j + 1 ))
  fi
  i=$(( i + 1 ))

#  uncomment: remove the '#' from the beginning of the line

#  echo "i=$i"  # uncomment to get debug output
done
#echo "n=$n"  # uncomment to get debug output 
#echo "j=$j"  # uncomment to get debug output
#echo "s=$s"  # uncomment to get debug output

echo "Is this what you want?"
echo "sum of $j even numbers ( <= $n ) = $s"
echo "or is this what you want?"

s=0
for ((i=1;i<=n;i++))
do
    echo -n "$(( 2*i )) "
    s=$(( s + 2*i ))
done
echo ""
echo "sum of $n even numbers = $s"

运行测试示例,

$ ./sum-of-even-numbers 
enter a number: 3
Is this what you want?
sum of 1 even numbers ( <= 3 ) = 2
or is this what you want?
2 4 6 
sum of 3 even numbers = 12

$ ./sum-of-even-numbers
enter a number: 4
Is this what you want?
sum of 2 even numbers ( <= 4 ) = 6
or is this what you want?
2 4 6 8 
sum of 4 even numbers = 20

$ ./sum-of-even-numbers
enter a number: 6
Is this what you want?
sum of 3 even numbers ( <= 6 ) = 12
or is this what you want?
2 4 6 8 10 12 
sum of 6 even numbers = 42

相关内容