Issue
I've been trying to figure a script for printing the Fibonacci Sequence but ran along some roadblocks.
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
Specifically on line 12-13, where it keeps printing
integer expression expected
in the terminal.
Any help would be greatly appreciated
Solution
The POSIX
manual for read. see here
NAME
read - read from standard input into shell variables
SYNOPSIS
read [-r] var...
DESCRIPTION
You should be using
read -r n
Well -r
is optional.
This solution is using $(())
for the math/arithmetic context.
#!/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
- I have added case statement to validate the user input if it is indeed an int.
- I did not change your whole code I just change/fix what was giving the error.
Add
-r
and-p
is not POSIX but the-r
is.Use
read n
if-p
is not working for you and use the echo to output some messages to stdout like what you did.
Answered By - Jetchisel Answer Checked By - Candace Johnson (WPSolving Volunteer)