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

时间:2015-04-21 21:15:45

标签: 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"

我必须创建菜单,我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用select

对于你的例子:

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