Saturday, October 8, 2022

[SOLVED] Case not accepting values of Select

Issue

I'm trying to send values of Select to Case but its not working as I expect.

I'm trying to match Cities with its country but only on value New York its showing correct answer country: USA in any other option it's sending to unknown

Please clerify where I'm making mistake

#!/bin/bash

select country in Switzerland, "Los Angeles", Moscow, Paris, London, Dubai, "New York";

do

case $country in

 "Los Angeles" | "New York")
    echo -n "country: USA"
    ;;


  Paris)
    echo -n "country: London"
    ;;


  "Dubai" )
    echo -n "Country: Abu-Dhabi"
    ;;

  *)
    echo -n "unknown"
    ;;

esac
done

Output: Working correctly only on New York

1) Switzerland,
2) Los Angeles,
3) Moscow,
4) Paris,
5) London,
6) Dubai,
7) New York
#? 7
country: USA#?

Error in any other option

1) Switzerland,
2) Los Angeles,
3) Moscow,
4) Paris,
5) London,
6) Dubai,
7) New York
#? 2
unknown#?

Solution

Remove the commas from inside your select country in Switzerland, "Los Angeles", Moscow, Paris, London, Dubai, "New York"; statement. The commas are being included in your "$country" variable in your case statement comparisons.

select country in Switzerland "Los Angeles" Moscow Paris London Dubai "New York";

Output:

$ ./script 
1) Switzerland  3) Moscow   5) London   7) New York
2) Los Angeles  4) Paris    6) Dubai
#? 1
unknown#? 2
country: USA#? 3
unknown#? 4
country: London#? 5
unknown#? 6
Country: Abu-Dhabi#? 7
country: USA#? 


Answered By - j_b
Answer Checked By - Pedro (WPSolving Volunteer)