Do you know what's wrong with my Fibonacci-Script, I get always the Error Message: ./fibonacci.sh: line 11: syntax error near unexpected token `do'
你知道我的fibonacci - script有什么问题吗?sh:第11行:在意外令牌“do”附近出现语法错误
#!/bin/bash
#fibonacci
echo "Geben Sie die n-te Fibonacci-Zahl ein:"
read n
if [$n -lt 2]; then
echo $n
else
array[0] = 0
array[1] = 1
for[k=2; $k -le $n; k++]; do
x = $array[0] + $array[1]
$array[0] = $array[1]
$array[1] = $x
done
echo $array[1]
fi
Please help!
请帮助!
1 个解决方案
#1
2
You had a few bugs inside. First, improper use of arrays. use curly braces if you use them. See here. Second, I redesigned your code with a while
loop - it is easier to understand. Third, bash doesn't like spaces in assignments.
里面有一些bug。首先,不恰当地使用数组。如果你使用花括号的话。在这里看到的。其次,我用while循环重新设计了您的代码——这样更容易理解。第三,bash不喜欢在作业中使用空格。
#!/bin/bash
#fibonacci
echo "Geben Sie die n-te Fibonacci-Zahl ein:"
read n
if [ $n -lt 2 ]; then
echo $n
else
array[0]=0
array[1]=1
k=2
while [ $k -le $n ]
do
let x=${array[0]}+${array[1]}
array[0]=${array[1]}
array[1]=$x
let k=$k+1
done
echo ${array[1]}
fi
example:
例子:
$ ./test.sh
Geben Sie die n-te Fibonacci-Zahl ein:
6
8
#1
2
You had a few bugs inside. First, improper use of arrays. use curly braces if you use them. See here. Second, I redesigned your code with a while
loop - it is easier to understand. Third, bash doesn't like spaces in assignments.
里面有一些bug。首先,不恰当地使用数组。如果你使用花括号的话。在这里看到的。其次,我用while循环重新设计了您的代码——这样更容易理解。第三,bash不喜欢在作业中使用空格。
#!/bin/bash
#fibonacci
echo "Geben Sie die n-te Fibonacci-Zahl ein:"
read n
if [ $n -lt 2 ]; then
echo $n
else
array[0]=0
array[1]=1
k=2
while [ $k -le $n ]
do
let x=${array[0]}+${array[1]}
array[0]=${array[1]}
array[1]=$x
let k=$k+1
done
echo ${array[1]}
fi
example:
例子:
$ ./test.sh
Geben Sie die n-te Fibonacci-Zahl ein:
6
8