user2271571
user2271571

Reputation: 11

Bash script declare

I am trying to create a simple bash script that will ask a user for input and then echo the value in the declares based on the number they choose.

declare -A bla
bla[1]="bla1"
bla[2]="bla2"

echo "What bla would you like?"
echo ""
echo "1) bla1"
echo "2) bla2"

read answer
echo "bla[$answer]"

When I run this script I am expecting the output to be either "bla1" or "bla2" depending if they typed 1 or 2. Although I only get the ouput: "bla[1]" or "bla[2]

What am I doing wrong here?

Upvotes: 0

Views: 139

Answers (2)

user2271571
user2271571

Reputation: 11

Figured it out I was using

#!/bin/sh instead of #!/bin/bash and needed to edit ${bla[$answer]}

Thanks for all the help.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247162

You want to use bash's select command here:

bla=( bla1 bla2 )
PS3="What bla would you like? "
select b in "${bla[@]}"; do
    [[ $b ]] && break
done
echo "you want: $b"

Notes:

  • a regular array suffices, you don't need an associative array if you're just using integer indices.
  • the array expansion "${bla[@]}" is required to expand the array into its constituent elements.
  • when the user enters a valid response, the $b variable will be non-null, and the break statement exits the select "loop".

Upvotes: 2

Related Questions