gpt4 book ai didi

linux - 循环 Bash Shell 脚本

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:37 37 4
gpt4 key购买 nike

我几乎是 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? "

最佳答案

#!/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

关于linux - 循环 Bash Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5641309/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com