Pill Beans Pill Beans - 7 months ago 14
Bash Question

new to Bash. Simple script

I am new to bash scripting and I am practicing some code.

I am trying to create a script that displays the following output and loops until the user types x or X

Menu 1

C) Calculation

X) Exit

C

Menu 2

Enter an integer or press X to exit:

22

Menu 3

+) Add

-) Subtract

+

Menu 2

Enter an integer or press X to exit:

33

The sum of 22 and 33 is 55

Menu 1

C) Calculation

X) Exit

c

Menu 2

Enter an integer or press X to exit:

50

Menu 3

+) Add

-) Subtract

-

Menu 2
Enter an integer or press X to exit:

23

The difference of 50 and 23 is 27

Menu 1

C) Calculation

X) Exit

X

Here is my code for it:

add ()
{

((sum=n1 + n2))
echo "The sum of $n1 and $n2 is $sum"
exit
}

subtract ()
{

((difference=n1 - n2))
echo "The difference of $n1 and $n2 is $difference"
exit
}


while true
do
echo "Menu 1"
echo "C) Calculation"
echo "X) Exit"

read opr


if [ ${opr} = 'x' ] || [ ${opr} = 'X' ]
then
break

elif [ ${opr} = 'c' ] || [ ${opr} = 'C' ]
then
echo "Menu 2"
echo "Enter an integer or press X to exit:"

fi

read n1

if [ $n1 = 'x' ] || [ $n1 = 'X' ]
then
break

else

echo "Menu3"
echo "+) Add"
echo "-) Subtract"

fi

read opr

if [ $opr = '+' ]
then

echo "Please enter another integer to perform addition"
read n2
add

elif [ $opr = '-' ]
echo "Please enter another integer to perform subtraction"
read n2
subtract

fi

done


I am receiving this error message:

./myscript.sh: line 72: syntax error near unexpected token
fi'
./myscript.sh: line 72:
fi'

I believe if I make menu1, menu2, and menu3 into functions I could achieve what I desire my output to be instead of this version of it.

But I know that I will still have a problem with those fi ... any idea where I should put them or what do I need to do for my code to work and not give an error?

Thanks

Pill

Answer

You simply forgot an then after elif

Look the general example from http://www.thegeekstuff.com/2010/06/bash-if-statement-examples/

If [ conditional expression1 ]
then
    statement1
    statement2
.
elif [ conditional expression2 ]
then
    statement3
    statement4
    .
.
.
else
    statement5 
fi

In your code:

...
elif [ $opr = '-' ]
then  <<<<<<< missing in your code!    
    echo "Please enter another integer to perform subtraction"
    read n2
    subtract

fi

EDIT: Why the program did not loop

If you write exit in your add and subtract method, your script will exit. Why it should not? Tip: remove both exit and the loop have a chance :-)