简体   繁体   中英

How can I create a menu in a shell script?

I want to create a select menu in it, like this:

echo "Choose your option:"

1) Factorial Calculation  
2) Addition Calculator  
3) Quit  

And I have some shell scripts;

Factorial

./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"

Addition

./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"

I have to create a menu, how should I proceed?

You can use select .

For your example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM