[我一直试图找到一个打印斐波那契数列的脚本,但遇到了一些障碍。
1 #!/bin/sh
2 echo "Program to Find Fibonacci Series"
3 echo "How many number of terms to be generated ?"
4 read
5 n=$REPLY
6 echo "Fibonacci Series up to $n terms :"
7 x=0
8 y=1
9 i=2
10 echo "$x"
11 echo "$y"
12 while [ $i -lt $n ]
13 do
14 i=`expr $i+1`
15 z=`expr $y+$x`
16 echo "$z"
17 x=$y
18 y=$z
19 done
20
21 exit 0
特别是在第12-13行,它继续打印
integer expression expected
在终端中。
任何帮助将不胜感激
此人将$(())
用于数学/算术上下文。
#!/bin/sh
echo "Program to Find Fibonacci Series"
read -rp "How many number of terms to be generated ? " n
case $n in
[!0-9]*) printf 'You entered %s which is not an int, please try again shall we?\n' "$n" >&2
exit 1;;
'') printf "Nothing was given, please try again..."
exit 1;;
esac
echo "Fibonacci Series up to $n terms :"
x=0 y=1 i=2
printf '%s\n' "$x" "$y"
while [ $i -lt $n ]; do
i=$((i+1))
z=$((y+x))
echo "$z"
x=$y
y=$z
done
-r
和-p
以阅读,我不确定-p
是否为POSIX,但是-r
为。