Shell Script for Menu

2019-07-10 01:46发布

问题:

I am making a new Menu Driven Shell Script in linux, I have simplified my table to just hello and bye to make this simpler, below is my basic menu layout

# Menu Shell Script
#
echo ----------------
echo     menu
echo ----------------
echo [1] hello
echo [2] bye
echo [3] exit
echo ----------------

Basically I have the menu, I have been playing around with a few things recently but cant seem to get anything working as I am new to this, I think then next line would be

`read -p "Please Select A Number: " menu_choice`

but I am not sure what to do with the variable and what not. I was wondering if anyone could help me with the next bit of code to simply get it to say hello when I press one, bye when 2 is pressed and exit when 3 when the user presses 3. It would be so much appreciated as I have been trying different ways for days and can't seem to get it to work.

回答1:

you don't need those backticks for echo... and read

echo "----------------"
echo "    menu"
echo "----------------"
echo "[1] hello"
echo "[2] bye"
echo "[3] exit"
echo "----------------"

read -p "Please Select A Number: " mc
if [[ "$mc" == "1" ]]; then
    echo "hello"
elif [[ "$mc" == "2" ]]; then
    echo "bye"
else
    echo "exit"
fi

Edit

showMenu(){

echo "----------------"
echo "    menu"
echo "----------------"
echo "[1] hello"
echo "[2] bye"
echo "[3] exit"
echo "----------------"

read -p "Please Select A Number: " mc
return $mc
}


while [[ "$m" != "3" ]]
do
    if [[ "$m" == "1" ]]; then
        echo "hello"

    elif [[ "$m" == "2" ]]; then
        echo "bye"
    fi
    showMenu
    m=$?
done

exit 0;


回答2:

Here is a sample

if [ $menu_choice -eq 1 ]
then
    echo hello
elif [ $menu_choice -eq 2 ]
then
    echo bye
elif [ $menu_choice -eq 3 ]
then
    exit 0
fi

or using case

case $menu_choice in
    1) echo hello
       ;;
    2) echo bye
       ;;
    3) exit 0
       ;;
esac