1

I'm trying to take elements from $Table_Header_Labels in a loop and have it grab the string of the same name to be used for string length. Ex: Grabbed "Apple" from the array and then convert it to grab $Apple to get the string to do ${#Apple}.

#!/bin/bash

# Create Array
declare -a Array=('Red' 'Blue' 'White');

# Set Variable
Red="Apples are Red!"

# Get Size of Variable from Array Element
for i in ${Array[0]}
do
    Element=${i}
    Element_Size="${i}_Size"

    # Print the generated one
    echo "$Element_Size = ${#Element}"

    # Print correct one to compare
    echo "Red_Size = ${#Red}"
    echo ""
done

Please take note I purposely made it so the loop only goes once. Currently, the Red_Size counts the array element itself which is three. I'm trying to get it to take the array element and grab the string assigned to the variable that is replicated by the array element.

Basic break down explanation: Apple => $Apple

Is this even possible with BASH?

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • In the code, I altered $Table_Header_Label to be $Array to make it easier to comprehend. – Casey McLaughlin Dec 02 '17 at 07:02
  • It's probably possible, but why do you want to do this? – melpomene Dec 02 '17 at 07:06
  • @melpomene There is a bit of code that is needed for everything that can quickly be put in a loop. Well out of everything there is a single bit of the code that requires you to have an outside variable called in. So somehow you would need the variable to be generated to grab it, for me, I'm just going to use the variable itself as the variable needing to be called for simplicity sake. – Casey McLaughlin Dec 04 '17 at 13:38

1 Answers1

0

To get the value of a variable whose name is in a variable, you can use the ${!name} syntax. For example, if i contains the name of a variable, "Red", to get the value of the variable Red, you can write ${!i}.

In your script:

Element=${!i}  # if $i is "Red" -> $Red -> "Apples are Red!"
janos
  • 120,954
  • 29
  • 226
  • 236