How to use a variable as part of an array name

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
9
down vote

favorite
6












I have two arrays:



arrayA=(1 2 3)
arrayB=(a b c)


and I want to print out one of them using a command line argument, i.e., without any if else.



I tried a few variations on the syntax with no success. I am wanting to do something like this:



ARG="$1"

echo $array$ARG[@]


but I get a "bad substitution" error. How can I achieve this?







share|improve this question




















  • This is emphatically not idiomatic bash. Please, don't do this.
    – Wildcard
    Nov 21 '17 at 6:10














up vote
9
down vote

favorite
6












I have two arrays:



arrayA=(1 2 3)
arrayB=(a b c)


and I want to print out one of them using a command line argument, i.e., without any if else.



I tried a few variations on the syntax with no success. I am wanting to do something like this:



ARG="$1"

echo $array$ARG[@]


but I get a "bad substitution" error. How can I achieve this?







share|improve this question




















  • This is emphatically not idiomatic bash. Please, don't do this.
    – Wildcard
    Nov 21 '17 at 6:10












up vote
9
down vote

favorite
6









up vote
9
down vote

favorite
6






6





I have two arrays:



arrayA=(1 2 3)
arrayB=(a b c)


and I want to print out one of them using a command line argument, i.e., without any if else.



I tried a few variations on the syntax with no success. I am wanting to do something like this:



ARG="$1"

echo $array$ARG[@]


but I get a "bad substitution" error. How can I achieve this?







share|improve this question












I have two arrays:



arrayA=(1 2 3)
arrayB=(a b c)


and I want to print out one of them using a command line argument, i.e., without any if else.



I tried a few variations on the syntax with no success. I am wanting to do something like this:



ARG="$1"

echo $array$ARG[@]


but I get a "bad substitution" error. How can I achieve this?









share|improve this question











share|improve this question




share|improve this question










asked Jan 7 '13 at 22:28









Aaron

4424714




4424714











  • This is emphatically not idiomatic bash. Please, don't do this.
    – Wildcard
    Nov 21 '17 at 6:10
















  • This is emphatically not idiomatic bash. Please, don't do this.
    – Wildcard
    Nov 21 '17 at 6:10















This is emphatically not idiomatic bash. Please, don't do this.
– Wildcard
Nov 21 '17 at 6:10




This is emphatically not idiomatic bash. Please, don't do this.
– Wildcard
Nov 21 '17 at 6:10










7 Answers
7






active

oldest

votes

















up vote
15
down vote



accepted










Try doing this :



$ arrayA=(1 2 3)
$ x=A
$ var=array$x[@]
$ echo $!var
1 2 3


NOTE



  • from man bash (parameter expansion) :


 $parameter
The value of parameter is substituted.
The braces are required when parameter is a positional parameter with
more than one


digit, or when parameter is followed by a character which
is not to be interpreted as part of its name.

* If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the
value of the variable formed from the rest of parameter as the
name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value
of parameter itself. This is known as indirect expansion.
* The exceptions to this are the expansions of $!prefix* and $!name[@] described below. The exclamation point must immediately
follow the left brace in order to introduce indirection.







share|improve this answer






















  • What exactly is the ! doing in front of the var variable? How does that work, it seemed to be history substitution on googling, but I couldn't see how that worked here.
    – Aaron
    Jan 7 '13 at 22:44










  • See my edited post
    – Gilles Quenot
    Jan 7 '13 at 22:53

















up vote
3
down vote













While you can use the indirect access as pointed in another answer, another way (in ksh and Bash 4.3 and newer) would be to use namerefs. Especially in the case of arrays this may be more useful since you can index the array through the nameref and don't need to put the index in the variable used as the reference.



arr1=(a b c)
arr2=(x y z)
typeset -n p=arr1 # or 'declare -n'
echo "$p[1]" # prints 'b'


This doesn't work through the indirect access:



q=arr2
echo "$!q" # prints 'x', the same as $arr2
echo "$!q[1]" # doesn't work, it tries to take q[1] as a reference


As a C programmer might put it, $!q[1] here acts as if q was an array of pointers, instead of being a pointer to an array.






share|improve this answer


















  • 1




    This works only  in bash version ≥ 4.3.
    – G-Man
    Dec 24 '17 at 16:10

















up vote
1
down vote













arrayA=(1 2 3)
arrayB=(a b c)

ARG="$1"

eval echo $array$ARG[@]

dataget ()
eval echo $array$1[$2:-@]

$ dataget A
1 2 3
$ dataget A 0
1
$ dataget B 1
b


note:
escap cotes in case of space!



eval dostuff "$array$1[$2:-@]"





share|improve this answer



























    up vote
    1
    down vote













    This took a lot of trial and error but eventually worked.



    I took some inspiration from Youness. But all other answers did not help on my old bash (suse11sp1[3.2.51(1)-release])



    The 'for' loop refused to expand the indirect array, instead you need to pre-expand it, use that to create another array with your new variable name. My example below shows a double loop, as that is my intended use.



    THEBIGLOOP=(New_FOO New_BAR)

    FOOthings=(1 2 3)
    BARthings=(a b c)

    for j in $THEBIGLOOP[*]
    do
    TheNewVariable=$(eval echo $$j#New_things[@])

    for i in $TheNewVariable
    do
    echo $j $i" hello"
    echo
    done
    done


    I'm using # to delete the "New_" from the first array entry, then concatenating with "things", to get "FOOthings".
    $ with echo and eval, then do their thing in order without throwing errors, which is wrapped in a new $() and assigned the new variable name.



    $ Test.sh

    New_FOO 1 hello

    New_FOO 2 hello

    New_FOO 3 hello

    New_BAR a hello

    New_BAR b hello

    New_BAR c hello


    UPDATE ##### 2018/06/07

    I've recently discovered one more spin on this issue. The variable created is not actually an array, but a space delimited string.
    For the task above this was ok, because of how "for" works, it doesn't read the array, it is expanded and then looped through, see extract below:



    for VARIABLE in 1 2 3 4 5 .. N
    do
    command1
    command2
    commandN
    done


    But, I then needed to use it as an array. For this I needed to perform one more step. I took code verbatim by Dennis Williamson. I've tested it and it works fine.



    IFS=', ' read -r -a TheNewVariable <<< $TheNewVariable[@]


    The "IFS=', '" is a variable containing your deliminator. "read" with "-a" cuts and feeds the sting back into the array variable. Note, this has no respect for quotation marks, but there are a few options in read to manage this, e.g. I've removed the -r flag which I didn't need.
    So I have now combined this addition in the variable creation, which allows the data to be treated and addressed as it should.



    THEBIGLOOP=(New_FOO New_BAR)

    FOOthings=(1 2 3)
    BARthings=(a b c)

    for j in $THEBIGLOOP[*]
    do

    IFS=', ' read -a TheNewVariable <<< $(eval echo $$j#New_things[@])

    for i in $TheNewVariable[@] #Now have to wrap with and expand with @
    do
    echo $j $i" hello"
    echo $TheNewVariable[$i] #This would not work in the original code
    echo
    done
    done





    share|improve this answer





























      up vote
      -1
      down vote













      no way :(



      if your arrays are that simple, then use associative arrays



       declare -A array
      array[A]="1 2 3"
      array[B]="a b c"


      unfortunately, if your arrays are more complicated ( for example array=( "a b" c ) ), that wouldn't work. Then, you need to think harder about another way to reach your goal.






      share|improve this answer




















      • What is the reason for the downvote? The associative array provides a nice way of grouping everything, assuming that my elements will all contain no space.
        – Aaron
        Jan 7 '13 at 23:45






      • 2




        @Aaron Assuming your elements don't contain spaces, that is a reasonable design. @watael I guess beginning the answer with “no way” when the primary focus of your question is clearly possible wasn't a good idea.
        – Gilles
        Jan 8 '13 at 0:12

















      up vote
      -1
      down vote













      Use eval



      arrayA=(1 2 3)
      ARG=arrayA
      eval echo $$ARG[@] # equivalent to eval echo $arrayA[@]
      # note that we escape the first '$' to prevent from
      # its parameter expansion before passing it to echo





      share|improve this answer





























        up vote
        -1
        down vote













        This is how you would create a dynamically named variable (bash version < 4.3).



        # Dynamically named array
        my_variable_name="dyn_arr_names"
        eval $my_variable_name=()

        # Adding by index to the array eg. dyn_arr_names[0]="bob"
        eval $my_variable_name[0]="bob"

        # Adding by pushing onto the array eg. dyn_arr_names+=(robert)
        eval $my_variable_name+=(robert)

        # Print value stored at index indirect
        echo $!my_variable_name[0]

        # Print value stored at index
        eval echo $$my_variable_name[0]

        # Get item count
        eval echo $#$my_variable_name[@]


        Below is a group of functions that can be used to manage dynamically named arrays (bash version < 4.3).



        # Dynamically create an array by name
        function arr()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        # The following line can be replaced with 'declare -ag $1=()'
        # Note: For some reason when using 'declare -ag $1' without the parentheses will make 'declare -p' fail
        eval $1=()


        # Insert incrementing by incrementing index eg. array+=(data)
        function arr_insert()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        eval $1[$(($#$1[@]))]=$2


        # Update an index by position
        function arr_set()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        eval $1[$2]=$3


        # Get the array content $array[@]
        function arr_get()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        eval echo $$1[@]


        # Get the value stored at a specific index eg. $array[0]
        function arr_at()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        [[ ! "$2" =~ ^(0

        # Get the value stored at a specific index eg. $array[0]
        function arr_count()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        local v=$1
        eval echo $#$1[@]




        array_names=(bob jane dick)

        for name in "$array_names[@]"
        do
        arr dyn_$name
        done

        echo "Arrays Created"
        declare -a | grep "a dyn_"

        # Insert three items per array
        for name in "$array_names[@]"
        do
        echo "Inserting dyn_$name abc"
        arr_insert dyn_$name "abc"
        echo "Inserting dyn_$name def"
        arr_insert dyn_$name "def"
        echo "Inserting dyn_$name ghi"
        arr_insert dyn_$name "ghi"
        done

        for name in "$array_names[@]"
        do
        echo "Setting dyn_$name[0]=first"
        arr_set dyn_$name 0 "first"
        echo "Setting dyn_$name[2]=third"
        arr_set dyn_$name 2 "third"
        done

        declare -a | grep "a dyn_"

        for name in "$array_names[@]"
        do
        arr_get dyn_$name
        done


        for name in "$array_names[@]"
        do
        echo "Dumping dyn_$name by index"
        # Print by index
        for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
        do
        echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

        done
        done

        for name in "$array_names[@]"
        do
        echo "Dumping dyn_$name"
        for n in $(arr_get dyn_$name)
        do
        echo $n
        done
        done


        Below is a group of functions that can be used to manage dynamically named arrays (bash version >= 4.3).



        # Dynamically create an array by name
        function arr()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -g -a $1=()


        # Insert incrementing by incrementing index eg. array+=(data)
        function arr_insert()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        declare -n r=$1
        r[$#r[@]]=$2


        # Update an index by position
        function arr_set()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        declare -n r=$1
        r[$2]=$3


        # Get the array content $array[@]
        function arr_get()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        declare -n r=$1
        echo $r[@]


        # Get the value stored at a specific index eg. $array[0]
        function arr_at()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        [[ ! "$2" =~ ^(0

        # Get the value stored at a specific index eg. $array[0]
        function arr_count()
        [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
        declare -p "$1" > /dev/null 2>&1
        [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
        declare -n r=$1
        echo $#r[@]




        array_names=(bob jane dick)

        for name in "$array_names[@]"
        do
        arr dyn_$name
        done

        echo "Arrays Created"
        declare -a | grep "a dyn_"

        # Insert three items per array
        for name in "$array_names[@]"
        do
        echo "Inserting dyn_$name abc"
        arr_insert dyn_$name "abc"
        echo "Inserting dyn_$name def"
        arr_insert dyn_$name "def"
        echo "Inserting dyn_$name ghi"
        arr_insert dyn_$name "ghi"
        done

        for name in "$array_names[@]"
        do
        echo "Setting dyn_$name[0]=first"
        arr_set dyn_$name 0 "first"
        echo "Setting dyn_$name[2]=third"
        arr_set dyn_$name 2 "third"
        done

        declare -a | grep 'a dyn_'

        for name in "$array_names[@]"
        do
        arr_get dyn_$name
        done


        for name in "$array_names[@]"
        do
        echo "Dumping dyn_$name by index"
        # Print by index
        for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
        do
        echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

        done
        done

        for name in "$array_names[@]"
        do
        echo "Dumping dyn_$name"
        for n in $(arr_get dyn_$name)
        do
        echo $n
        done
        done


        For more details on these examples visit Getting Bashed by Dynamic Arrays by Ludvik Jerabek






        share|improve this answer






















          Your Answer







          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "106"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f60584%2fhow-to-use-a-variable-as-part-of-an-array-name%23new-answer', 'question_page');

          );

          Post as a guest






























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          15
          down vote



          accepted










          Try doing this :



          $ arrayA=(1 2 3)
          $ x=A
          $ var=array$x[@]
          $ echo $!var
          1 2 3


          NOTE



          • from man bash (parameter expansion) :


           $parameter
          The value of parameter is substituted.
          The braces are required when parameter is a positional parameter with
          more than one


          digit, or when parameter is followed by a character which
          is not to be interpreted as part of its name.

          * If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the
          value of the variable formed from the rest of parameter as the
          name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value
          of parameter itself. This is known as indirect expansion.
          * The exceptions to this are the expansions of $!prefix* and $!name[@] described below. The exclamation point must immediately
          follow the left brace in order to introduce indirection.







          share|improve this answer






















          • What exactly is the ! doing in front of the var variable? How does that work, it seemed to be history substitution on googling, but I couldn't see how that worked here.
            – Aaron
            Jan 7 '13 at 22:44










          • See my edited post
            – Gilles Quenot
            Jan 7 '13 at 22:53














          up vote
          15
          down vote



          accepted










          Try doing this :



          $ arrayA=(1 2 3)
          $ x=A
          $ var=array$x[@]
          $ echo $!var
          1 2 3


          NOTE



          • from man bash (parameter expansion) :


           $parameter
          The value of parameter is substituted.
          The braces are required when parameter is a positional parameter with
          more than one


          digit, or when parameter is followed by a character which
          is not to be interpreted as part of its name.

          * If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the
          value of the variable formed from the rest of parameter as the
          name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value
          of parameter itself. This is known as indirect expansion.
          * The exceptions to this are the expansions of $!prefix* and $!name[@] described below. The exclamation point must immediately
          follow the left brace in order to introduce indirection.







          share|improve this answer






















          • What exactly is the ! doing in front of the var variable? How does that work, it seemed to be history substitution on googling, but I couldn't see how that worked here.
            – Aaron
            Jan 7 '13 at 22:44










          • See my edited post
            – Gilles Quenot
            Jan 7 '13 at 22:53












          up vote
          15
          down vote



          accepted







          up vote
          15
          down vote



          accepted






          Try doing this :



          $ arrayA=(1 2 3)
          $ x=A
          $ var=array$x[@]
          $ echo $!var
          1 2 3


          NOTE



          • from man bash (parameter expansion) :


           $parameter
          The value of parameter is substituted.
          The braces are required when parameter is a positional parameter with
          more than one


          digit, or when parameter is followed by a character which
          is not to be interpreted as part of its name.

          * If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the
          value of the variable formed from the rest of parameter as the
          name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value
          of parameter itself. This is known as indirect expansion.
          * The exceptions to this are the expansions of $!prefix* and $!name[@] described below. The exclamation point must immediately
          follow the left brace in order to introduce indirection.







          share|improve this answer














          Try doing this :



          $ arrayA=(1 2 3)
          $ x=A
          $ var=array$x[@]
          $ echo $!var
          1 2 3


          NOTE



          • from man bash (parameter expansion) :


           $parameter
          The value of parameter is substituted.
          The braces are required when parameter is a positional parameter with
          more than one


          digit, or when parameter is followed by a character which
          is not to be interpreted as part of its name.

          * If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the
          value of the variable formed from the rest of parameter as the
          name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value
          of parameter itself. This is known as indirect expansion.
          * The exceptions to this are the expansions of $!prefix* and $!name[@] described below. The exclamation point must immediately
          follow the left brace in order to introduce indirection.








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 7 '13 at 22:53

























          answered Jan 7 '13 at 22:35









          Gilles Quenot

          15.3k13449




          15.3k13449











          • What exactly is the ! doing in front of the var variable? How does that work, it seemed to be history substitution on googling, but I couldn't see how that worked here.
            – Aaron
            Jan 7 '13 at 22:44










          • See my edited post
            – Gilles Quenot
            Jan 7 '13 at 22:53
















          • What exactly is the ! doing in front of the var variable? How does that work, it seemed to be history substitution on googling, but I couldn't see how that worked here.
            – Aaron
            Jan 7 '13 at 22:44










          • See my edited post
            – Gilles Quenot
            Jan 7 '13 at 22:53















          What exactly is the ! doing in front of the var variable? How does that work, it seemed to be history substitution on googling, but I couldn't see how that worked here.
          – Aaron
          Jan 7 '13 at 22:44




          What exactly is the ! doing in front of the var variable? How does that work, it seemed to be history substitution on googling, but I couldn't see how that worked here.
          – Aaron
          Jan 7 '13 at 22:44












          See my edited post
          – Gilles Quenot
          Jan 7 '13 at 22:53




          See my edited post
          – Gilles Quenot
          Jan 7 '13 at 22:53












          up vote
          3
          down vote













          While you can use the indirect access as pointed in another answer, another way (in ksh and Bash 4.3 and newer) would be to use namerefs. Especially in the case of arrays this may be more useful since you can index the array through the nameref and don't need to put the index in the variable used as the reference.



          arr1=(a b c)
          arr2=(x y z)
          typeset -n p=arr1 # or 'declare -n'
          echo "$p[1]" # prints 'b'


          This doesn't work through the indirect access:



          q=arr2
          echo "$!q" # prints 'x', the same as $arr2
          echo "$!q[1]" # doesn't work, it tries to take q[1] as a reference


          As a C programmer might put it, $!q[1] here acts as if q was an array of pointers, instead of being a pointer to an array.






          share|improve this answer


















          • 1




            This works only  in bash version ≥ 4.3.
            – G-Man
            Dec 24 '17 at 16:10














          up vote
          3
          down vote













          While you can use the indirect access as pointed in another answer, another way (in ksh and Bash 4.3 and newer) would be to use namerefs. Especially in the case of arrays this may be more useful since you can index the array through the nameref and don't need to put the index in the variable used as the reference.



          arr1=(a b c)
          arr2=(x y z)
          typeset -n p=arr1 # or 'declare -n'
          echo "$p[1]" # prints 'b'


          This doesn't work through the indirect access:



          q=arr2
          echo "$!q" # prints 'x', the same as $arr2
          echo "$!q[1]" # doesn't work, it tries to take q[1] as a reference


          As a C programmer might put it, $!q[1] here acts as if q was an array of pointers, instead of being a pointer to an array.






          share|improve this answer


















          • 1




            This works only  in bash version ≥ 4.3.
            – G-Man
            Dec 24 '17 at 16:10












          up vote
          3
          down vote










          up vote
          3
          down vote









          While you can use the indirect access as pointed in another answer, another way (in ksh and Bash 4.3 and newer) would be to use namerefs. Especially in the case of arrays this may be more useful since you can index the array through the nameref and don't need to put the index in the variable used as the reference.



          arr1=(a b c)
          arr2=(x y z)
          typeset -n p=arr1 # or 'declare -n'
          echo "$p[1]" # prints 'b'


          This doesn't work through the indirect access:



          q=arr2
          echo "$!q" # prints 'x', the same as $arr2
          echo "$!q[1]" # doesn't work, it tries to take q[1] as a reference


          As a C programmer might put it, $!q[1] here acts as if q was an array of pointers, instead of being a pointer to an array.






          share|improve this answer














          While you can use the indirect access as pointed in another answer, another way (in ksh and Bash 4.3 and newer) would be to use namerefs. Especially in the case of arrays this may be more useful since you can index the array through the nameref and don't need to put the index in the variable used as the reference.



          arr1=(a b c)
          arr2=(x y z)
          typeset -n p=arr1 # or 'declare -n'
          echo "$p[1]" # prints 'b'


          This doesn't work through the indirect access:



          q=arr2
          echo "$!q" # prints 'x', the same as $arr2
          echo "$!q[1]" # doesn't work, it tries to take q[1] as a reference


          As a C programmer might put it, $!q[1] here acts as if q was an array of pointers, instead of being a pointer to an array.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 24 '17 at 20:59

























          answered Dec 24 '17 at 13:47









          ilkkachu

          49.9k674137




          49.9k674137







          • 1




            This works only  in bash version ≥ 4.3.
            – G-Man
            Dec 24 '17 at 16:10












          • 1




            This works only  in bash version ≥ 4.3.
            – G-Man
            Dec 24 '17 at 16:10







          1




          1




          This works only  in bash version ≥ 4.3.
          – G-Man
          Dec 24 '17 at 16:10




          This works only  in bash version ≥ 4.3.
          – G-Man
          Dec 24 '17 at 16:10










          up vote
          1
          down vote













          arrayA=(1 2 3)
          arrayB=(a b c)

          ARG="$1"

          eval echo $array$ARG[@]

          dataget ()
          eval echo $array$1[$2:-@]

          $ dataget A
          1 2 3
          $ dataget A 0
          1
          $ dataget B 1
          b


          note:
          escap cotes in case of space!



          eval dostuff "$array$1[$2:-@]"





          share|improve this answer
























            up vote
            1
            down vote













            arrayA=(1 2 3)
            arrayB=(a b c)

            ARG="$1"

            eval echo $array$ARG[@]

            dataget ()
            eval echo $array$1[$2:-@]

            $ dataget A
            1 2 3
            $ dataget A 0
            1
            $ dataget B 1
            b


            note:
            escap cotes in case of space!



            eval dostuff "$array$1[$2:-@]"





            share|improve this answer






















              up vote
              1
              down vote










              up vote
              1
              down vote









              arrayA=(1 2 3)
              arrayB=(a b c)

              ARG="$1"

              eval echo $array$ARG[@]

              dataget ()
              eval echo $array$1[$2:-@]

              $ dataget A
              1 2 3
              $ dataget A 0
              1
              $ dataget B 1
              b


              note:
              escap cotes in case of space!



              eval dostuff "$array$1[$2:-@]"





              share|improve this answer












              arrayA=(1 2 3)
              arrayB=(a b c)

              ARG="$1"

              eval echo $array$ARG[@]

              dataget ()
              eval echo $array$1[$2:-@]

              $ dataget A
              1 2 3
              $ dataget A 0
              1
              $ dataget B 1
              b


              note:
              escap cotes in case of space!



              eval dostuff "$array$1[$2:-@]"






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 24 '17 at 22:55









              Jonas

              873415




              873415




















                  up vote
                  1
                  down vote













                  This took a lot of trial and error but eventually worked.



                  I took some inspiration from Youness. But all other answers did not help on my old bash (suse11sp1[3.2.51(1)-release])



                  The 'for' loop refused to expand the indirect array, instead you need to pre-expand it, use that to create another array with your new variable name. My example below shows a double loop, as that is my intended use.



                  THEBIGLOOP=(New_FOO New_BAR)

                  FOOthings=(1 2 3)
                  BARthings=(a b c)

                  for j in $THEBIGLOOP[*]
                  do
                  TheNewVariable=$(eval echo $$j#New_things[@])

                  for i in $TheNewVariable
                  do
                  echo $j $i" hello"
                  echo
                  done
                  done


                  I'm using # to delete the "New_" from the first array entry, then concatenating with "things", to get "FOOthings".
                  $ with echo and eval, then do their thing in order without throwing errors, which is wrapped in a new $() and assigned the new variable name.



                  $ Test.sh

                  New_FOO 1 hello

                  New_FOO 2 hello

                  New_FOO 3 hello

                  New_BAR a hello

                  New_BAR b hello

                  New_BAR c hello


                  UPDATE ##### 2018/06/07

                  I've recently discovered one more spin on this issue. The variable created is not actually an array, but a space delimited string.
                  For the task above this was ok, because of how "for" works, it doesn't read the array, it is expanded and then looped through, see extract below:



                  for VARIABLE in 1 2 3 4 5 .. N
                  do
                  command1
                  command2
                  commandN
                  done


                  But, I then needed to use it as an array. For this I needed to perform one more step. I took code verbatim by Dennis Williamson. I've tested it and it works fine.



                  IFS=', ' read -r -a TheNewVariable <<< $TheNewVariable[@]


                  The "IFS=', '" is a variable containing your deliminator. "read" with "-a" cuts and feeds the sting back into the array variable. Note, this has no respect for quotation marks, but there are a few options in read to manage this, e.g. I've removed the -r flag which I didn't need.
                  So I have now combined this addition in the variable creation, which allows the data to be treated and addressed as it should.



                  THEBIGLOOP=(New_FOO New_BAR)

                  FOOthings=(1 2 3)
                  BARthings=(a b c)

                  for j in $THEBIGLOOP[*]
                  do

                  IFS=', ' read -a TheNewVariable <<< $(eval echo $$j#New_things[@])

                  for i in $TheNewVariable[@] #Now have to wrap with and expand with @
                  do
                  echo $j $i" hello"
                  echo $TheNewVariable[$i] #This would not work in the original code
                  echo
                  done
                  done





                  share|improve this answer


























                    up vote
                    1
                    down vote













                    This took a lot of trial and error but eventually worked.



                    I took some inspiration from Youness. But all other answers did not help on my old bash (suse11sp1[3.2.51(1)-release])



                    The 'for' loop refused to expand the indirect array, instead you need to pre-expand it, use that to create another array with your new variable name. My example below shows a double loop, as that is my intended use.



                    THEBIGLOOP=(New_FOO New_BAR)

                    FOOthings=(1 2 3)
                    BARthings=(a b c)

                    for j in $THEBIGLOOP[*]
                    do
                    TheNewVariable=$(eval echo $$j#New_things[@])

                    for i in $TheNewVariable
                    do
                    echo $j $i" hello"
                    echo
                    done
                    done


                    I'm using # to delete the "New_" from the first array entry, then concatenating with "things", to get "FOOthings".
                    $ with echo and eval, then do their thing in order without throwing errors, which is wrapped in a new $() and assigned the new variable name.



                    $ Test.sh

                    New_FOO 1 hello

                    New_FOO 2 hello

                    New_FOO 3 hello

                    New_BAR a hello

                    New_BAR b hello

                    New_BAR c hello


                    UPDATE ##### 2018/06/07

                    I've recently discovered one more spin on this issue. The variable created is not actually an array, but a space delimited string.
                    For the task above this was ok, because of how "for" works, it doesn't read the array, it is expanded and then looped through, see extract below:



                    for VARIABLE in 1 2 3 4 5 .. N
                    do
                    command1
                    command2
                    commandN
                    done


                    But, I then needed to use it as an array. For this I needed to perform one more step. I took code verbatim by Dennis Williamson. I've tested it and it works fine.



                    IFS=', ' read -r -a TheNewVariable <<< $TheNewVariable[@]


                    The "IFS=', '" is a variable containing your deliminator. "read" with "-a" cuts and feeds the sting back into the array variable. Note, this has no respect for quotation marks, but there are a few options in read to manage this, e.g. I've removed the -r flag which I didn't need.
                    So I have now combined this addition in the variable creation, which allows the data to be treated and addressed as it should.



                    THEBIGLOOP=(New_FOO New_BAR)

                    FOOthings=(1 2 3)
                    BARthings=(a b c)

                    for j in $THEBIGLOOP[*]
                    do

                    IFS=', ' read -a TheNewVariable <<< $(eval echo $$j#New_things[@])

                    for i in $TheNewVariable[@] #Now have to wrap with and expand with @
                    do
                    echo $j $i" hello"
                    echo $TheNewVariable[$i] #This would not work in the original code
                    echo
                    done
                    done





                    share|improve this answer
























                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      This took a lot of trial and error but eventually worked.



                      I took some inspiration from Youness. But all other answers did not help on my old bash (suse11sp1[3.2.51(1)-release])



                      The 'for' loop refused to expand the indirect array, instead you need to pre-expand it, use that to create another array with your new variable name. My example below shows a double loop, as that is my intended use.



                      THEBIGLOOP=(New_FOO New_BAR)

                      FOOthings=(1 2 3)
                      BARthings=(a b c)

                      for j in $THEBIGLOOP[*]
                      do
                      TheNewVariable=$(eval echo $$j#New_things[@])

                      for i in $TheNewVariable
                      do
                      echo $j $i" hello"
                      echo
                      done
                      done


                      I'm using # to delete the "New_" from the first array entry, then concatenating with "things", to get "FOOthings".
                      $ with echo and eval, then do their thing in order without throwing errors, which is wrapped in a new $() and assigned the new variable name.



                      $ Test.sh

                      New_FOO 1 hello

                      New_FOO 2 hello

                      New_FOO 3 hello

                      New_BAR a hello

                      New_BAR b hello

                      New_BAR c hello


                      UPDATE ##### 2018/06/07

                      I've recently discovered one more spin on this issue. The variable created is not actually an array, but a space delimited string.
                      For the task above this was ok, because of how "for" works, it doesn't read the array, it is expanded and then looped through, see extract below:



                      for VARIABLE in 1 2 3 4 5 .. N
                      do
                      command1
                      command2
                      commandN
                      done


                      But, I then needed to use it as an array. For this I needed to perform one more step. I took code verbatim by Dennis Williamson. I've tested it and it works fine.



                      IFS=', ' read -r -a TheNewVariable <<< $TheNewVariable[@]


                      The "IFS=', '" is a variable containing your deliminator. "read" with "-a" cuts and feeds the sting back into the array variable. Note, this has no respect for quotation marks, but there are a few options in read to manage this, e.g. I've removed the -r flag which I didn't need.
                      So I have now combined this addition in the variable creation, which allows the data to be treated and addressed as it should.



                      THEBIGLOOP=(New_FOO New_BAR)

                      FOOthings=(1 2 3)
                      BARthings=(a b c)

                      for j in $THEBIGLOOP[*]
                      do

                      IFS=', ' read -a TheNewVariable <<< $(eval echo $$j#New_things[@])

                      for i in $TheNewVariable[@] #Now have to wrap with and expand with @
                      do
                      echo $j $i" hello"
                      echo $TheNewVariable[$i] #This would not work in the original code
                      echo
                      done
                      done





                      share|improve this answer














                      This took a lot of trial and error but eventually worked.



                      I took some inspiration from Youness. But all other answers did not help on my old bash (suse11sp1[3.2.51(1)-release])



                      The 'for' loop refused to expand the indirect array, instead you need to pre-expand it, use that to create another array with your new variable name. My example below shows a double loop, as that is my intended use.



                      THEBIGLOOP=(New_FOO New_BAR)

                      FOOthings=(1 2 3)
                      BARthings=(a b c)

                      for j in $THEBIGLOOP[*]
                      do
                      TheNewVariable=$(eval echo $$j#New_things[@])

                      for i in $TheNewVariable
                      do
                      echo $j $i" hello"
                      echo
                      done
                      done


                      I'm using # to delete the "New_" from the first array entry, then concatenating with "things", to get "FOOthings".
                      $ with echo and eval, then do their thing in order without throwing errors, which is wrapped in a new $() and assigned the new variable name.



                      $ Test.sh

                      New_FOO 1 hello

                      New_FOO 2 hello

                      New_FOO 3 hello

                      New_BAR a hello

                      New_BAR b hello

                      New_BAR c hello


                      UPDATE ##### 2018/06/07

                      I've recently discovered one more spin on this issue. The variable created is not actually an array, but a space delimited string.
                      For the task above this was ok, because of how "for" works, it doesn't read the array, it is expanded and then looped through, see extract below:



                      for VARIABLE in 1 2 3 4 5 .. N
                      do
                      command1
                      command2
                      commandN
                      done


                      But, I then needed to use it as an array. For this I needed to perform one more step. I took code verbatim by Dennis Williamson. I've tested it and it works fine.



                      IFS=', ' read -r -a TheNewVariable <<< $TheNewVariable[@]


                      The "IFS=', '" is a variable containing your deliminator. "read" with "-a" cuts and feeds the sting back into the array variable. Note, this has no respect for quotation marks, but there are a few options in read to manage this, e.g. I've removed the -r flag which I didn't need.
                      So I have now combined this addition in the variable creation, which allows the data to be treated and addressed as it should.



                      THEBIGLOOP=(New_FOO New_BAR)

                      FOOthings=(1 2 3)
                      BARthings=(a b c)

                      for j in $THEBIGLOOP[*]
                      do

                      IFS=', ' read -a TheNewVariable <<< $(eval echo $$j#New_things[@])

                      for i in $TheNewVariable[@] #Now have to wrap with and expand with @
                      do
                      echo $j $i" hello"
                      echo $TheNewVariable[$i] #This would not work in the original code
                      echo
                      done
                      done






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jun 7 at 12:15

























                      answered May 15 at 11:07









                      Stripy42

                      112




                      112




















                          up vote
                          -1
                          down vote













                          no way :(



                          if your arrays are that simple, then use associative arrays



                           declare -A array
                          array[A]="1 2 3"
                          array[B]="a b c"


                          unfortunately, if your arrays are more complicated ( for example array=( "a b" c ) ), that wouldn't work. Then, you need to think harder about another way to reach your goal.






                          share|improve this answer




















                          • What is the reason for the downvote? The associative array provides a nice way of grouping everything, assuming that my elements will all contain no space.
                            – Aaron
                            Jan 7 '13 at 23:45






                          • 2




                            @Aaron Assuming your elements don't contain spaces, that is a reasonable design. @watael I guess beginning the answer with “no way” when the primary focus of your question is clearly possible wasn't a good idea.
                            – Gilles
                            Jan 8 '13 at 0:12














                          up vote
                          -1
                          down vote













                          no way :(



                          if your arrays are that simple, then use associative arrays



                           declare -A array
                          array[A]="1 2 3"
                          array[B]="a b c"


                          unfortunately, if your arrays are more complicated ( for example array=( "a b" c ) ), that wouldn't work. Then, you need to think harder about another way to reach your goal.






                          share|improve this answer




















                          • What is the reason for the downvote? The associative array provides a nice way of grouping everything, assuming that my elements will all contain no space.
                            – Aaron
                            Jan 7 '13 at 23:45






                          • 2




                            @Aaron Assuming your elements don't contain spaces, that is a reasonable design. @watael I guess beginning the answer with “no way” when the primary focus of your question is clearly possible wasn't a good idea.
                            – Gilles
                            Jan 8 '13 at 0:12












                          up vote
                          -1
                          down vote










                          up vote
                          -1
                          down vote









                          no way :(



                          if your arrays are that simple, then use associative arrays



                           declare -A array
                          array[A]="1 2 3"
                          array[B]="a b c"


                          unfortunately, if your arrays are more complicated ( for example array=( "a b" c ) ), that wouldn't work. Then, you need to think harder about another way to reach your goal.






                          share|improve this answer












                          no way :(



                          if your arrays are that simple, then use associative arrays



                           declare -A array
                          array[A]="1 2 3"
                          array[B]="a b c"


                          unfortunately, if your arrays are more complicated ( for example array=( "a b" c ) ), that wouldn't work. Then, you need to think harder about another way to reach your goal.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 7 '13 at 22:41









                          watael

                          69154




                          69154











                          • What is the reason for the downvote? The associative array provides a nice way of grouping everything, assuming that my elements will all contain no space.
                            – Aaron
                            Jan 7 '13 at 23:45






                          • 2




                            @Aaron Assuming your elements don't contain spaces, that is a reasonable design. @watael I guess beginning the answer with “no way” when the primary focus of your question is clearly possible wasn't a good idea.
                            – Gilles
                            Jan 8 '13 at 0:12
















                          • What is the reason for the downvote? The associative array provides a nice way of grouping everything, assuming that my elements will all contain no space.
                            – Aaron
                            Jan 7 '13 at 23:45






                          • 2




                            @Aaron Assuming your elements don't contain spaces, that is a reasonable design. @watael I guess beginning the answer with “no way” when the primary focus of your question is clearly possible wasn't a good idea.
                            – Gilles
                            Jan 8 '13 at 0:12















                          What is the reason for the downvote? The associative array provides a nice way of grouping everything, assuming that my elements will all contain no space.
                          – Aaron
                          Jan 7 '13 at 23:45




                          What is the reason for the downvote? The associative array provides a nice way of grouping everything, assuming that my elements will all contain no space.
                          – Aaron
                          Jan 7 '13 at 23:45




                          2




                          2




                          @Aaron Assuming your elements don't contain spaces, that is a reasonable design. @watael I guess beginning the answer with “no way” when the primary focus of your question is clearly possible wasn't a good idea.
                          – Gilles
                          Jan 8 '13 at 0:12




                          @Aaron Assuming your elements don't contain spaces, that is a reasonable design. @watael I guess beginning the answer with “no way” when the primary focus of your question is clearly possible wasn't a good idea.
                          – Gilles
                          Jan 8 '13 at 0:12










                          up vote
                          -1
                          down vote













                          Use eval



                          arrayA=(1 2 3)
                          ARG=arrayA
                          eval echo $$ARG[@] # equivalent to eval echo $arrayA[@]
                          # note that we escape the first '$' to prevent from
                          # its parameter expansion before passing it to echo





                          share|improve this answer


























                            up vote
                            -1
                            down vote













                            Use eval



                            arrayA=(1 2 3)
                            ARG=arrayA
                            eval echo $$ARG[@] # equivalent to eval echo $arrayA[@]
                            # note that we escape the first '$' to prevent from
                            # its parameter expansion before passing it to echo





                            share|improve this answer
























                              up vote
                              -1
                              down vote










                              up vote
                              -1
                              down vote









                              Use eval



                              arrayA=(1 2 3)
                              ARG=arrayA
                              eval echo $$ARG[@] # equivalent to eval echo $arrayA[@]
                              # note that we escape the first '$' to prevent from
                              # its parameter expansion before passing it to echo





                              share|improve this answer














                              Use eval



                              arrayA=(1 2 3)
                              ARG=arrayA
                              eval echo $$ARG[@] # equivalent to eval echo $arrayA[@]
                              # note that we escape the first '$' to prevent from
                              # its parameter expansion before passing it to echo






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 4 '14 at 18:59

























                              answered Apr 4 '14 at 18:54









                              MS.Kim

                              67221116




                              67221116




















                                  up vote
                                  -1
                                  down vote













                                  This is how you would create a dynamically named variable (bash version < 4.3).



                                  # Dynamically named array
                                  my_variable_name="dyn_arr_names"
                                  eval $my_variable_name=()

                                  # Adding by index to the array eg. dyn_arr_names[0]="bob"
                                  eval $my_variable_name[0]="bob"

                                  # Adding by pushing onto the array eg. dyn_arr_names+=(robert)
                                  eval $my_variable_name+=(robert)

                                  # Print value stored at index indirect
                                  echo $!my_variable_name[0]

                                  # Print value stored at index
                                  eval echo $$my_variable_name[0]

                                  # Get item count
                                  eval echo $#$my_variable_name[@]


                                  Below is a group of functions that can be used to manage dynamically named arrays (bash version < 4.3).



                                  # Dynamically create an array by name
                                  function arr()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  # The following line can be replaced with 'declare -ag $1=()'
                                  # Note: For some reason when using 'declare -ag $1' without the parentheses will make 'declare -p' fail
                                  eval $1=()


                                  # Insert incrementing by incrementing index eg. array+=(data)
                                  function arr_insert()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  eval $1[$(($#$1[@]))]=$2


                                  # Update an index by position
                                  function arr_set()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  eval $1[$2]=$3


                                  # Get the array content $array[@]
                                  function arr_get()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  eval echo $$1[@]


                                  # Get the value stored at a specific index eg. $array[0]
                                  function arr_at()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  [[ ! "$2" =~ ^(0

                                  # Get the value stored at a specific index eg. $array[0]
                                  function arr_count()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  local v=$1
                                  eval echo $#$1[@]




                                  array_names=(bob jane dick)

                                  for name in "$array_names[@]"
                                  do
                                  arr dyn_$name
                                  done

                                  echo "Arrays Created"
                                  declare -a | grep "a dyn_"

                                  # Insert three items per array
                                  for name in "$array_names[@]"
                                  do
                                  echo "Inserting dyn_$name abc"
                                  arr_insert dyn_$name "abc"
                                  echo "Inserting dyn_$name def"
                                  arr_insert dyn_$name "def"
                                  echo "Inserting dyn_$name ghi"
                                  arr_insert dyn_$name "ghi"
                                  done

                                  for name in "$array_names[@]"
                                  do
                                  echo "Setting dyn_$name[0]=first"
                                  arr_set dyn_$name 0 "first"
                                  echo "Setting dyn_$name[2]=third"
                                  arr_set dyn_$name 2 "third"
                                  done

                                  declare -a | grep "a dyn_"

                                  for name in "$array_names[@]"
                                  do
                                  arr_get dyn_$name
                                  done


                                  for name in "$array_names[@]"
                                  do
                                  echo "Dumping dyn_$name by index"
                                  # Print by index
                                  for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                  do
                                  echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                  done
                                  done

                                  for name in "$array_names[@]"
                                  do
                                  echo "Dumping dyn_$name"
                                  for n in $(arr_get dyn_$name)
                                  do
                                  echo $n
                                  done
                                  done


                                  Below is a group of functions that can be used to manage dynamically named arrays (bash version >= 4.3).



                                  # Dynamically create an array by name
                                  function arr()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -g -a $1=()


                                  # Insert incrementing by incrementing index eg. array+=(data)
                                  function arr_insert()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  declare -n r=$1
                                  r[$#r[@]]=$2


                                  # Update an index by position
                                  function arr_set()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  declare -n r=$1
                                  r[$2]=$3


                                  # Get the array content $array[@]
                                  function arr_get()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  declare -n r=$1
                                  echo $r[@]


                                  # Get the value stored at a specific index eg. $array[0]
                                  function arr_at()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  [[ ! "$2" =~ ^(0

                                  # Get the value stored at a specific index eg. $array[0]
                                  function arr_count()
                                  [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                  declare -p "$1" > /dev/null 2>&1
                                  [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                  declare -n r=$1
                                  echo $#r[@]




                                  array_names=(bob jane dick)

                                  for name in "$array_names[@]"
                                  do
                                  arr dyn_$name
                                  done

                                  echo "Arrays Created"
                                  declare -a | grep "a dyn_"

                                  # Insert three items per array
                                  for name in "$array_names[@]"
                                  do
                                  echo "Inserting dyn_$name abc"
                                  arr_insert dyn_$name "abc"
                                  echo "Inserting dyn_$name def"
                                  arr_insert dyn_$name "def"
                                  echo "Inserting dyn_$name ghi"
                                  arr_insert dyn_$name "ghi"
                                  done

                                  for name in "$array_names[@]"
                                  do
                                  echo "Setting dyn_$name[0]=first"
                                  arr_set dyn_$name 0 "first"
                                  echo "Setting dyn_$name[2]=third"
                                  arr_set dyn_$name 2 "third"
                                  done

                                  declare -a | grep 'a dyn_'

                                  for name in "$array_names[@]"
                                  do
                                  arr_get dyn_$name
                                  done


                                  for name in "$array_names[@]"
                                  do
                                  echo "Dumping dyn_$name by index"
                                  # Print by index
                                  for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                  do
                                  echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                  done
                                  done

                                  for name in "$array_names[@]"
                                  do
                                  echo "Dumping dyn_$name"
                                  for n in $(arr_get dyn_$name)
                                  do
                                  echo $n
                                  done
                                  done


                                  For more details on these examples visit Getting Bashed by Dynamic Arrays by Ludvik Jerabek






                                  share|improve this answer


























                                    up vote
                                    -1
                                    down vote













                                    This is how you would create a dynamically named variable (bash version < 4.3).



                                    # Dynamically named array
                                    my_variable_name="dyn_arr_names"
                                    eval $my_variable_name=()

                                    # Adding by index to the array eg. dyn_arr_names[0]="bob"
                                    eval $my_variable_name[0]="bob"

                                    # Adding by pushing onto the array eg. dyn_arr_names+=(robert)
                                    eval $my_variable_name+=(robert)

                                    # Print value stored at index indirect
                                    echo $!my_variable_name[0]

                                    # Print value stored at index
                                    eval echo $$my_variable_name[0]

                                    # Get item count
                                    eval echo $#$my_variable_name[@]


                                    Below is a group of functions that can be used to manage dynamically named arrays (bash version < 4.3).



                                    # Dynamically create an array by name
                                    function arr()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    # The following line can be replaced with 'declare -ag $1=()'
                                    # Note: For some reason when using 'declare -ag $1' without the parentheses will make 'declare -p' fail
                                    eval $1=()


                                    # Insert incrementing by incrementing index eg. array+=(data)
                                    function arr_insert()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    eval $1[$(($#$1[@]))]=$2


                                    # Update an index by position
                                    function arr_set()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    eval $1[$2]=$3


                                    # Get the array content $array[@]
                                    function arr_get()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    eval echo $$1[@]


                                    # Get the value stored at a specific index eg. $array[0]
                                    function arr_at()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    [[ ! "$2" =~ ^(0

                                    # Get the value stored at a specific index eg. $array[0]
                                    function arr_count()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    local v=$1
                                    eval echo $#$1[@]




                                    array_names=(bob jane dick)

                                    for name in "$array_names[@]"
                                    do
                                    arr dyn_$name
                                    done

                                    echo "Arrays Created"
                                    declare -a | grep "a dyn_"

                                    # Insert three items per array
                                    for name in "$array_names[@]"
                                    do
                                    echo "Inserting dyn_$name abc"
                                    arr_insert dyn_$name "abc"
                                    echo "Inserting dyn_$name def"
                                    arr_insert dyn_$name "def"
                                    echo "Inserting dyn_$name ghi"
                                    arr_insert dyn_$name "ghi"
                                    done

                                    for name in "$array_names[@]"
                                    do
                                    echo "Setting dyn_$name[0]=first"
                                    arr_set dyn_$name 0 "first"
                                    echo "Setting dyn_$name[2]=third"
                                    arr_set dyn_$name 2 "third"
                                    done

                                    declare -a | grep "a dyn_"

                                    for name in "$array_names[@]"
                                    do
                                    arr_get dyn_$name
                                    done


                                    for name in "$array_names[@]"
                                    do
                                    echo "Dumping dyn_$name by index"
                                    # Print by index
                                    for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                    do
                                    echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                    done
                                    done

                                    for name in "$array_names[@]"
                                    do
                                    echo "Dumping dyn_$name"
                                    for n in $(arr_get dyn_$name)
                                    do
                                    echo $n
                                    done
                                    done


                                    Below is a group of functions that can be used to manage dynamically named arrays (bash version >= 4.3).



                                    # Dynamically create an array by name
                                    function arr()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -g -a $1=()


                                    # Insert incrementing by incrementing index eg. array+=(data)
                                    function arr_insert()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    declare -n r=$1
                                    r[$#r[@]]=$2


                                    # Update an index by position
                                    function arr_set()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    declare -n r=$1
                                    r[$2]=$3


                                    # Get the array content $array[@]
                                    function arr_get()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    declare -n r=$1
                                    echo $r[@]


                                    # Get the value stored at a specific index eg. $array[0]
                                    function arr_at()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    [[ ! "$2" =~ ^(0

                                    # Get the value stored at a specific index eg. $array[0]
                                    function arr_count()
                                    [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                    declare -p "$1" > /dev/null 2>&1
                                    [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                    declare -n r=$1
                                    echo $#r[@]




                                    array_names=(bob jane dick)

                                    for name in "$array_names[@]"
                                    do
                                    arr dyn_$name
                                    done

                                    echo "Arrays Created"
                                    declare -a | grep "a dyn_"

                                    # Insert three items per array
                                    for name in "$array_names[@]"
                                    do
                                    echo "Inserting dyn_$name abc"
                                    arr_insert dyn_$name "abc"
                                    echo "Inserting dyn_$name def"
                                    arr_insert dyn_$name "def"
                                    echo "Inserting dyn_$name ghi"
                                    arr_insert dyn_$name "ghi"
                                    done

                                    for name in "$array_names[@]"
                                    do
                                    echo "Setting dyn_$name[0]=first"
                                    arr_set dyn_$name 0 "first"
                                    echo "Setting dyn_$name[2]=third"
                                    arr_set dyn_$name 2 "third"
                                    done

                                    declare -a | grep 'a dyn_'

                                    for name in "$array_names[@]"
                                    do
                                    arr_get dyn_$name
                                    done


                                    for name in "$array_names[@]"
                                    do
                                    echo "Dumping dyn_$name by index"
                                    # Print by index
                                    for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                    do
                                    echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                    done
                                    done

                                    for name in "$array_names[@]"
                                    do
                                    echo "Dumping dyn_$name"
                                    for n in $(arr_get dyn_$name)
                                    do
                                    echo $n
                                    done
                                    done


                                    For more details on these examples visit Getting Bashed by Dynamic Arrays by Ludvik Jerabek






                                    share|improve this answer
























                                      up vote
                                      -1
                                      down vote










                                      up vote
                                      -1
                                      down vote









                                      This is how you would create a dynamically named variable (bash version < 4.3).



                                      # Dynamically named array
                                      my_variable_name="dyn_arr_names"
                                      eval $my_variable_name=()

                                      # Adding by index to the array eg. dyn_arr_names[0]="bob"
                                      eval $my_variable_name[0]="bob"

                                      # Adding by pushing onto the array eg. dyn_arr_names+=(robert)
                                      eval $my_variable_name+=(robert)

                                      # Print value stored at index indirect
                                      echo $!my_variable_name[0]

                                      # Print value stored at index
                                      eval echo $$my_variable_name[0]

                                      # Get item count
                                      eval echo $#$my_variable_name[@]


                                      Below is a group of functions that can be used to manage dynamically named arrays (bash version < 4.3).



                                      # Dynamically create an array by name
                                      function arr()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      # The following line can be replaced with 'declare -ag $1=()'
                                      # Note: For some reason when using 'declare -ag $1' without the parentheses will make 'declare -p' fail
                                      eval $1=()


                                      # Insert incrementing by incrementing index eg. array+=(data)
                                      function arr_insert()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      eval $1[$(($#$1[@]))]=$2


                                      # Update an index by position
                                      function arr_set()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      eval $1[$2]=$3


                                      # Get the array content $array[@]
                                      function arr_get()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      eval echo $$1[@]


                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_at()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      [[ ! "$2" =~ ^(0

                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_count()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      local v=$1
                                      eval echo $#$1[@]




                                      array_names=(bob jane dick)

                                      for name in "$array_names[@]"
                                      do
                                      arr dyn_$name
                                      done

                                      echo "Arrays Created"
                                      declare -a | grep "a dyn_"

                                      # Insert three items per array
                                      for name in "$array_names[@]"
                                      do
                                      echo "Inserting dyn_$name abc"
                                      arr_insert dyn_$name "abc"
                                      echo "Inserting dyn_$name def"
                                      arr_insert dyn_$name "def"
                                      echo "Inserting dyn_$name ghi"
                                      arr_insert dyn_$name "ghi"
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Setting dyn_$name[0]=first"
                                      arr_set dyn_$name 0 "first"
                                      echo "Setting dyn_$name[2]=third"
                                      arr_set dyn_$name 2 "third"
                                      done

                                      declare -a | grep "a dyn_"

                                      for name in "$array_names[@]"
                                      do
                                      arr_get dyn_$name
                                      done


                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name by index"
                                      # Print by index
                                      for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                      do
                                      echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                      done
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name"
                                      for n in $(arr_get dyn_$name)
                                      do
                                      echo $n
                                      done
                                      done


                                      Below is a group of functions that can be used to manage dynamically named arrays (bash version >= 4.3).



                                      # Dynamically create an array by name
                                      function arr()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -g -a $1=()


                                      # Insert incrementing by incrementing index eg. array+=(data)
                                      function arr_insert()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      r[$#r[@]]=$2


                                      # Update an index by position
                                      function arr_set()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      r[$2]=$3


                                      # Get the array content $array[@]
                                      function arr_get()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      echo $r[@]


                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_at()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      [[ ! "$2" =~ ^(0

                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_count()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      echo $#r[@]




                                      array_names=(bob jane dick)

                                      for name in "$array_names[@]"
                                      do
                                      arr dyn_$name
                                      done

                                      echo "Arrays Created"
                                      declare -a | grep "a dyn_"

                                      # Insert three items per array
                                      for name in "$array_names[@]"
                                      do
                                      echo "Inserting dyn_$name abc"
                                      arr_insert dyn_$name "abc"
                                      echo "Inserting dyn_$name def"
                                      arr_insert dyn_$name "def"
                                      echo "Inserting dyn_$name ghi"
                                      arr_insert dyn_$name "ghi"
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Setting dyn_$name[0]=first"
                                      arr_set dyn_$name 0 "first"
                                      echo "Setting dyn_$name[2]=third"
                                      arr_set dyn_$name 2 "third"
                                      done

                                      declare -a | grep 'a dyn_'

                                      for name in "$array_names[@]"
                                      do
                                      arr_get dyn_$name
                                      done


                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name by index"
                                      # Print by index
                                      for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                      do
                                      echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                      done
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name"
                                      for n in $(arr_get dyn_$name)
                                      do
                                      echo $n
                                      done
                                      done


                                      For more details on these examples visit Getting Bashed by Dynamic Arrays by Ludvik Jerabek






                                      share|improve this answer














                                      This is how you would create a dynamically named variable (bash version < 4.3).



                                      # Dynamically named array
                                      my_variable_name="dyn_arr_names"
                                      eval $my_variable_name=()

                                      # Adding by index to the array eg. dyn_arr_names[0]="bob"
                                      eval $my_variable_name[0]="bob"

                                      # Adding by pushing onto the array eg. dyn_arr_names+=(robert)
                                      eval $my_variable_name+=(robert)

                                      # Print value stored at index indirect
                                      echo $!my_variable_name[0]

                                      # Print value stored at index
                                      eval echo $$my_variable_name[0]

                                      # Get item count
                                      eval echo $#$my_variable_name[@]


                                      Below is a group of functions that can be used to manage dynamically named arrays (bash version < 4.3).



                                      # Dynamically create an array by name
                                      function arr()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      # The following line can be replaced with 'declare -ag $1=()'
                                      # Note: For some reason when using 'declare -ag $1' without the parentheses will make 'declare -p' fail
                                      eval $1=()


                                      # Insert incrementing by incrementing index eg. array+=(data)
                                      function arr_insert()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      eval $1[$(($#$1[@]))]=$2


                                      # Update an index by position
                                      function arr_set()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      eval $1[$2]=$3


                                      # Get the array content $array[@]
                                      function arr_get()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      eval echo $$1[@]


                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_at()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      [[ ! "$2" =~ ^(0

                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_count()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      local v=$1
                                      eval echo $#$1[@]




                                      array_names=(bob jane dick)

                                      for name in "$array_names[@]"
                                      do
                                      arr dyn_$name
                                      done

                                      echo "Arrays Created"
                                      declare -a | grep "a dyn_"

                                      # Insert three items per array
                                      for name in "$array_names[@]"
                                      do
                                      echo "Inserting dyn_$name abc"
                                      arr_insert dyn_$name "abc"
                                      echo "Inserting dyn_$name def"
                                      arr_insert dyn_$name "def"
                                      echo "Inserting dyn_$name ghi"
                                      arr_insert dyn_$name "ghi"
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Setting dyn_$name[0]=first"
                                      arr_set dyn_$name 0 "first"
                                      echo "Setting dyn_$name[2]=third"
                                      arr_set dyn_$name 2 "third"
                                      done

                                      declare -a | grep "a dyn_"

                                      for name in "$array_names[@]"
                                      do
                                      arr_get dyn_$name
                                      done


                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name by index"
                                      # Print by index
                                      for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                      do
                                      echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                      done
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name"
                                      for n in $(arr_get dyn_$name)
                                      do
                                      echo $n
                                      done
                                      done


                                      Below is a group of functions that can be used to manage dynamically named arrays (bash version >= 4.3).



                                      # Dynamically create an array by name
                                      function arr()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -g -a $1=()


                                      # Insert incrementing by incrementing index eg. array+=(data)
                                      function arr_insert()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      r[$#r[@]]=$2


                                      # Update an index by position
                                      function arr_set()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      r[$2]=$3


                                      # Get the array content $array[@]
                                      function arr_get()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      echo $r[@]


                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_at()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable" 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      [[ ! "$2" =~ ^(0

                                      # Get the value stored at a specific index eg. $array[0]
                                      function arr_count()
                                      [[ ! "$1" =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] && echo "Invalid bash variable " 1>&2 ; return 1 ;
                                      declare -p "$1" > /dev/null 2>&1
                                      [[ $? -eq 1 ]] && echo "Bash variable [$1] doesn't exist" 1>&2 ; return 1 ;
                                      declare -n r=$1
                                      echo $#r[@]




                                      array_names=(bob jane dick)

                                      for name in "$array_names[@]"
                                      do
                                      arr dyn_$name
                                      done

                                      echo "Arrays Created"
                                      declare -a | grep "a dyn_"

                                      # Insert three items per array
                                      for name in "$array_names[@]"
                                      do
                                      echo "Inserting dyn_$name abc"
                                      arr_insert dyn_$name "abc"
                                      echo "Inserting dyn_$name def"
                                      arr_insert dyn_$name "def"
                                      echo "Inserting dyn_$name ghi"
                                      arr_insert dyn_$name "ghi"
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Setting dyn_$name[0]=first"
                                      arr_set dyn_$name 0 "first"
                                      echo "Setting dyn_$name[2]=third"
                                      arr_set dyn_$name 2 "third"
                                      done

                                      declare -a | grep 'a dyn_'

                                      for name in "$array_names[@]"
                                      do
                                      arr_get dyn_$name
                                      done


                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name by index"
                                      # Print by index
                                      for (( i=0 ; i < $(arr_count dyn_$name) ; i++ ))
                                      do
                                      echo "dyn_$name[$i]: $(arr_at dyn_$name $i)"

                                      done
                                      done

                                      for name in "$array_names[@]"
                                      do
                                      echo "Dumping dyn_$name"
                                      for n in $(arr_get dyn_$name)
                                      do
                                      echo $n
                                      done
                                      done


                                      For more details on these examples visit Getting Bashed by Dynamic Arrays by Ludvik Jerabek







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Aug 26 '15 at 3:07

























                                      answered Aug 25 '15 at 1:24









                                      NOPx90

                                      11




                                      11






















                                           

                                          draft saved


                                          draft discarded


























                                           


                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f60584%2fhow-to-use-a-variable-as-part-of-an-array-name%23new-answer', 'question_page');

                                          );

                                          Post as a guest













































































                                          Popular posts from this blog

                                          How to check contact read email or not when send email to Individual?

                                          Displaying single band from multi-band raster using QGIS

                                          How many registers does an x86_64 CPU actually have?