0

Im writing a script that prompts the user to pick one of three choices, depending on the choice the prompt should echo back a line.

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

But it doesnt work, I type in one of the choices in the prompt when it asks for it but I get back :line 28: syntax error: unexpected end of line

I dont know whats wrong, i have spacing between the brackets and I end the code with fi.

Edward
  • 1

1 Answers1

4

For shell menus, select is the way to go:

#!/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

In addition, note the use of a case statement instead of multiple if and else statements. case should always be preferred for simple statements with 2 or more options. However, case does not allow for the more complex logics as [[ ]] in Bash.


For your code, lack of indentation is hiding the errors:

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

You are missing fi for two if statements.

There are other logic errors, but this is the cause of the syntax errors.

Artur Meinild
  • 26,018
glenn jackman
  • 17,900