案例陈述帮助

Fil*_*ppo 1 bash shell-script case

我对 Unix 很陌生,我需要关于这个案例陈述的帮助。我想要做的是让用户选择一个带有case语句的变量,然后让系统读取用户所做选择的结果。这是我的脚本结构(例如):

CHOOSEfruit () {
clear
echo "Choose fruit you need to buy (a.Apple b.Banana c.Pear d.Pineapple)"
read FRUIT
case $FRUIT in
    a|A)
    echo "Apple"
    ;;
    b|B)
    echo "Banana"
    ;;
    c|C)
    echo "Pear"
    ;;
    d|D)
    echo "Pineapple"
    ;;
esac
clear
echo "The fruit you need to buy is $FRUIT"
echo ""
read -p "Press [Enter] key to go back to main menu"
clear
}
Run Code Online (Sandbox Code Playgroud)

如果我选择“a”,我希望我的脚本输出:“你需要买的水果是苹果”

Kus*_*nda 5

这可以通过select循环更好地解决:

PS3='Please select fruit from the menu: '

select fruit in 'No fruit please' Apple Banana Pear Pineapple; do
    case $REPLY in
        1)
            # User wants no fruit
            unset fruit
            break
            ;;
        [2-5])
            # All ok, exit loop
            break
            ;;
        *)
            # Invalid choice
            echo 'Try again' >&2
    esac
done

if [ -n "$fruit" ]; then
    printf 'The fruit you need is %s\n' "$fruit"
else
    echo 'You selected no fruit!'
fi
Run Code Online (Sandbox Code Playgroud)

该select循环在交互式菜单中向用户呈现选择列表。给用户从菜单中选择项目的提示是 中的字符串$PS3。

在select循环体中,值 in$fruit将是用户选择的实际文本字符串,而$REPLY将是用户在提示符下键入的任何内容。

请注意,不需要case ... esac在循环中使用语句。您可以在此处使用任何代码。例如,您可能会觉得使用更舒服if ... then ... elif ... else ... fi:

if [ "$REPLY" = 1 ]; then
    unset fruit
    break
elif [[ $REPLY == [2-5] ]]; then
    break
else
    echo 'Try again' >&2
fi
Run Code Online (Sandbox Code Playgroud)

在select退出循环使用break,就像任何其他的无限循环。

这段代码的三个运行:

if [ "$REPLY" = 1 ]; then
    unset fruit
    break
elif [[ $REPLY == [2-5] ]]; then
    break
else
    echo 'Try again' >&2
fi
Run Code Online (Sandbox Code Playgroud)
$ bash script
1) No fruit please
2) Apple
3) Banana
4) Pear
5) Pineapple
Please select fruit from the menu: 1
You selected no fruit!
Run Code Online (Sandbox Code Playgroud)
$ bash script
1) No fruit please
2) Apple
3) Banana
4) Pear
5) Pineapple
Please select fruit from the menu: 2
The fruit you need is Apple
Run Code Online (Sandbox Code Playgroud)