Barceloniak
Barceloniak

Reputation: 13

Bash - Multiple choice, user input

I am quite new in bash and would like to link appropriate choice with profile parameters for that user. Problem is that is not recognize my selection

I have already tried to test but have had syntax error near unexpected token `newline'

> echo "Name? Use, alphabetic letter from multiple choice. 
a)Donald
b)Alan 
c)Brian"

  read -p "Insert appropriate letter a, b or c" don ala br

  echo "Perfect" $don 
  echo "Perfect, OK" $ala 
  echo "Perfect, Nice" $br

  case "$dev" 
  echo "OK" 
  esac

I would like to hit letter and enter afterwards go to case where define params for the profile. I have encountered below error: syntax error near unexpected token `newline'

Upvotes: 1

Views: 5591

Answers (3)

gojimmypi
gojimmypi

Reputation: 526

Here's something that will restrict the input to only a, b, c; allowing upper or lower case; waiting for one of those values.

Putting the upper case value in THIS_SELECTION and then using it in a case statement:

#!/bin/bash
echo "Name? Use, alphabetic letter from multiple choice. 
    a)Donald
    b)Alan 
    c)Brian"

THIS_SELECTION=
until [ "${THIS_SELECTION^}" == "A" ] || [ "${THIS_SELECTION^}" == "B" ] || [ "${THIS_SELECTION^}" == "C" ]; do
    read -n1 -p "Insert appropriate letter a, b or c: "  THIS_SELECTION
    THIS_SELECTION=${THIS_SELECTION^}
    echo;
done 

case "${THIS_SELECTION}" in
    A) echo A Donald ;;
    B) echo B Alan ;;
    C) echo C Brian ;;
    *) echo other ;;
esac

Upvotes: 0

chepner
chepner

Reputation: 531125

Your current read command tries to split the input into 3 words, assigning each piece to one of don, ala, br. You just want to read one word, and compare it to each of a, b, or c. You can do this with a case statement:

read -p "Insert appropriate letter a, b, or c" choice

case $choice in
  a) echo "Perfect $choice" ;;
  b) echo "Perfect, OK $choice" ;;
  c) echo "Perfect, Nice $choice" ;;
  *) echo "Unrecognized selection: $choice" ;;
esac

Upvotes: 2

choroba
choroba

Reputation: 241848

select is usually used for command line menus. It normally expects only one answer, but you can tweak it for example in the following way:

#! /bin/bash

names=(Donald Alan Brian)
selected=()
PS3='Name? You can select multiple space separated options: '
select name in "${names[@]}" ; do
    for reply in $REPLY ; do
        selected+=(${names[reply - 1]})
    done
    [[ $selected ]] && break
done
echo Selected: "${selected[@]}"

Upvotes: 3

Related Questions