我对linux很陌生,我写了一个简单的bash shell脚本,要求用户输入一个数字,然后要求另一个数字并显示数字的总和和乘积。我对此没有任何问题,但我想循环脚本。
例如,我想询问用户是否要退出,如果他们选择不退出,则脚本重新开始并再次请求两个号码。如果那里有人知道关于循环的东西,你能帮帮我吗?谢谢。
这是我的代码:
#!/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? "
答案 0 :(得分:3)
#!/bin/bash
# Initialize quit so we enter the outer loop first time
quit="N"
# Loop while quit is N
while [ "$quit" = "N" ]
do
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"
#reset quit - so we enter the inner loop first time
quit=""
#we want to repeat until quit is Y or N:
#while quit is not "Y" and quit is not "N"
while [ "$quit" != "Y" -a "$quit" != "N" ]
do
echo "Would you like to quit? Y/N?"
read quit
#Convert lower case y/n to Y/N
quit=`echo $quit | tr yn YN`
done
done
答案 1 :(得分:2)
while [[ "$(read -p "Quit?" q;echo $q)" != "y" ]] ; do
echo okay, go on
done
答案 2 :(得分:0)
以下是循环的快速示例:
#!/bin/env bash
let quit="N"
while [ $quit != "Y" ]; do
echo "To quit, enter Y:"
read quit
done
答案 3 :(得分:0)
最简单的方法是永久循环并在用户退出时中断:
while true
do
read -p "Continue to loop? " answer
[ "n" = "$answer" ] && break
done
echo "Now I'm here!"
break
命令会使您脱离当前循环并在循环之后继续。不需要标志变量。
顺便说一下:
[ "n" = "$answer" ] && break
与:
相同if [ "n" = "$answer" ]
then
break
fi
请注意-p
命令中提示符的read
。这样,您可以同时提示和读取变量。您还可以在echo语句中使用\c
来禁止使用新行,或使用不执行 NL 的printf
:
read -p "What do you want? " wants #Prompt on the same line as the read
echo "What are your desires? \c" #Prompt on the same line as the read
read desires
printf "What are your hopes? " #Prompt on the same line as the read
read hopes
希望这有帮助。
答案 4 :(得分:0)
#!/bin/bash
function sumAndProd {
read -p "enter a number: " number1
read -p "enter another number: " number2
echo "Thank you $name"
sum=$((number1+number2))
prod=$((number1*$number2))
echo "The sum of the two numbers is: $sum"
echo "The product of the two numbers is: $prod"
}
read -p "Name please? " name
quit=N
while [[ "$quit" != Y ]]
do
sumAndProd
read -p "Would you like to quit? Y/N? " quit
done
这是更多的代码审查。
while (cond) ; do {block} done
#是一种循环形式。let
。对于算术表达式,x = $((表达式))更常见。 echo The sum is $((number1+number2))
答案 5 :(得分:0)
#!/bin/sh
while true
do
/var/www/bash/grep_ffmpeg.sh
sleep 15
done
循环使用nohup