2

I'm looking to use a for loop to assign several variables using essentially the same code.

#!bin/bash
for (( i=1; i<=4; i++ )); do
    case ${i} in 
        1) filling=apple; a=an ;; 
        2) filling=peach; a=a ;; 
        3) filling=pecan; a=a ;; 
        4) filling=cherry; a=a ;;
    esac
    echo "Would you like ${a} ${filling} pie? Y/N"
    read var1
    case ${var1} in
       Y|y) ${filling}_pie="True" ;; 
       N|n) ${filling}_pie="No" ;;
    esac
done

This script works exactly as intended except when it comes to assignign the variables at the end. I get apple_pie=True: command not found. I've also tried Y|y) ${${filling}}_pie="True" ;, but when I do that I get bash: ${${filling}}_pie="True": bad substitution.

Either my shell hates pie, or I'm doing something wrong but I can't seem to find an instance of anybody else doing this, or at least I can't an instance of anybody describing it the way I'm trying to describe it when I search on Google...

Is there anyway to get this to assign a variable while using a variable in the assignment?

lcd047
  • 5,521
  • 1
  • 25
  • 35
mkingsbu
  • 334
  • 3
  • 18
  • 2
    You basically want a dynamic name for your variable (get help [here](http://stackoverflow.com/questions/16553089/bash-dynamic-variable-names)) – Eugeniu Rosca Jun 25 '15 at 20:39

1 Answers1

2

You can use declare directive here for declaring dynamic variables:

declare ${filling}_pie="True"
anubhava
  • 713,503
  • 59
  • 514
  • 593