I'm pretty much brand new to linux, and I've written a simple bash shell script that asks a user for a number and then asks for another number and displays the sum and product of the numbers. I have no problems with this, but I'm wanting to loop the script.
For instances, I want to ask the user if they want to quit, and if they choose not to quit the script starts over and asks for two numbers again. If there's anyone out there who knows stuff about loops, could you help me out please? Thanks.
Here's my code:
#!/bin/bash
echo -n "Name please? "
read name
echo "enter a number."
read number1
echo "enter another number"
read number2
echo "Thank you $name"
let i=0
let i=$number1+$number2
let x=0
let x=$number1*$number2
echo "The sum of the two numbers is: $i"
echo "The product of the two numbers is: $x"
echo "Would you like to quit? Y/N? "
quit=N
while [ "$quit" = "Y" ]
do
clear
while ["$quit" != "Y" ]
do
echo "enter a number."
read number1
echo "enter another number"
read number2
echo "Thank you $name"
let i=0
let i=$number1+$number2
let x=0
let x=$number1*$number2
echo "The sum of the two numbers is: $i"
echo "The product of the two numbers is: $x"
echo "Would you like to quit? Y/N? "
loop with nohup
Here is a quick example of loops:
This is more a code-review.
while (cond) ; do {block} done
# is a form of loop.let
very often. For arithmetic expressions, x=$((expression)) is far more common.echo The sum is $((number1+number2))
The easiest thing to do is to loop forever and break when the user quits:
The
break
command breaks you out of the current loop and continues right after the loop. No need for a flag variable.By the way:
Is the same as:
Note the
-p
for the prompt in theread
command. That way, you can prompt and read the variable at the same time. You can also use\c
in echo statements to suppress the New Line, or useprintf
which doesn't do a NL:Hope this helps.