linux - 如何在 shell 脚本中创建菜单?

标签 linux bash shell unix menu

我想在其中创建一个选择菜单,如下所示:

echo "Choose your option:"

1) Factorial Calculation  
2) Addition Calculator  
3) Quit  

我有一些 shell 脚本;

阶乘

./fact.sh

#!/bin/bash
fact=1
#taking input from user
echo -e "enter a number"
read n
#if enter value less than 0
if [ $n -le 0 ] ; then
echo "invalid number"
exit
fi
#factorial logic
if [ $n -gt 0 ] ; then
for((i=$n;i>=1;i--))
do
fact=`expr $fact \* $i`
done
fi
echo "The factorial of $n is $fact"

添加

./add.sh

#!/bin/bash
#function to add two numbers
add()
{
x=$1
y=$2
echo -e "Number entered by u are: $x and $y"
echo "sum of $1 and $2 is `expr $x + $y` "
}
# main script
echo "enter first number"
read first
echo "enter second number"
read sec
#calling function
add $first $sec
echo "end of the script"

我必须创建一个菜单,我应该如何进行?

最佳答案

您可以使用选择

以你的例子为例:

select option in Factorial Addition Quit; do
case "$option" in
    "Factorial")
        echo "Factorial"
        break ;;
    "Addition")
        echo "Addition"
        break ;;
    "Quit") exit ;;
esac
done

关于linux - 如何在 shell 脚本中创建菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783254/

相关文章:

linux - sudo bang bang 到底是什么?

linux - 如何使用 sed 或 awk 正则表达式在 linux shell 中解析此数据

检查另一个程序是否打开了文件

PHP文件夹权限问题

linux - grep 查找包含 jboss 的行- 直到下一个/

bash - 脚本始终从/而不是当前目录运行

linux - Bash:tail 的语法高亮显示(使用 awk)

bash - 如何确定我所在的当前交互式 shell(命令行)

linux - 为 Redis 3.2.6 调整 Linux 内核堆栈

linux - 从unix中的倒数第二行删除一个字符