linux - 循环 Bash Shell 脚本

标签 linux bash shell loops

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

相关文章:

python - 如何在 linux 中模拟

linux - 如何获知GNU parallel一次最多可以运行多少个进程?

linux - 特定端口的 tcp 连接列表

arrays - 从字符串数组中选取有效的 IP

bash - bash 脚本中的读取与 sleep

linux - shell脚本重命名文件夹中的文件保持顺序

linux - 没有换行的cat文件

bash - 如何将程序的 stdout 和 stderr 重定向到一个文件,并将相同的 stderr 重定向到另一个文件?

linux - 检查返回值的 shell 方法的错误代码

php - 在 CakePHP shell 中搜索