我有这段代码
#!/bin/bash
read num
sum=0
i=1
while [$i -le $num]; do
let sum=$sum+1
let i=$i+1
done
echo $sum
我收到错误./test:第5行:[1:命令未找到,但我不确定这部分是错误的,无法找到。
答案 0 :(得分:1)
您可以使用算术扩展:
#!/bin/bash
# This function does safe read of a number
read_number ()
{
read x
# Check for an actual number
case "$x" in ""|*[^0-9]*) echo "Not a number" >&2; exit 1;; esac
# Consider base 10
echo "$((10#$x))"
}
num=$(read_number)
sum=0
i=1
while ((i <= num)); do
((sum++, i++))
done
echo $sum