需要有关初学者 Bash 脚本的帮助

需要有关初学者 Bash 脚本的帮助

我正在编写一个脚本,提示用户从三个选项中选择一个,根据选择,提示应该回显一行。

"!/bin/bash
first=chocolate
second=vanilla
third=strawberry
echo "Which would you choose?"
read -p "chocolate,vanilla or strawberry?"
if [ $first ];
then
echo "Chocolate! good choice"
else
echo "Not a valid choice"
if [ $second ];
then
echo "vanilla! good choice"
else
echo "Not a valid choice"
if [ $third ];
then
echo "Strawberry! good choice"
else
echo "Not a valid choice"
fi

但它不起作用,当提示要求时,我输入了其中一个选项,但我得到的结果是:第 28 行:语法错误:意外的行尾

我不知道哪里出了问题,括号之间有空格,并且我以 fi 结束代码。

答案1

对于 shell 菜单,select要走的路是:

#!/usr/bin/env bash
PS3="Which would you choose? "
select choice in chocolate vanilla strawberry; do
    case $choice in
        vanilla)
            echo "${choice}! good choice"
            break
            ;;
        chocolate|strawberry)
            echo "Not the correct choice"
            break
            ;;
        # otherwise, reply was not one of the choices: stay in the menu.
    esac
done

此外,请注意使用一个case语句而不是多个ifandelse语句。case对于具有 2 个或更多选项的简单语句,应始终优先使用。但是,case不允许像[[ ]]Bash 中那样使用更复杂的逻辑。


对于您的代码,缺少缩进会隐藏错误:

if [ $first ];
then
    echo "Chocolate! good choice"
else
    echo "Not a valid choice"
    if [ $second ];
    then
        echo "vanilla! good choice"
    else
        echo "Not a valid choice"
        if [ $third ];
        then
            echo "Strawberry! good choice"
        else
            echo "Not a valid choice"
        fi

您缺少fi两条if陈述。

还有其他逻辑错误,但这是语法错误的原因。

相关内容