无法找到命令

时间:2014-10-30 00:41:34

标签: linux bash shell unix command

我有这段代码

#!/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:命令未找到,但我不确定这部分是错误的,无法找到。

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