Results 1 to 5 of 5

Thread: bash: assinging array to a dynamic variable

  1. #1
    Join Date
    May 2005
    Location
    Russia
    Beans
    537

    bash: assinging array to a dynamic variable

    Good day, everyone!

    I have an array I want to assign to a dynamic variable. If I want to do it for a string - I do:
    Code:
    #!/bin/bash
    
    getVar() {
      eval $1="'$2'"
    }
    
    getVar FOO "bar"
    echo $FOO
    exit 0
    But it doesn't work out with arrays... Please help me! Thanks in advance!
    Last edited by PryGuy; August 31st, 2010 at 01:26 PM.

  2. #2
    Join Date
    Sep 2007
    Location
    England
    Beans
    1,103

    Re: bash: assinging array to a dynamic variable

    you'll probably have to loop through all array items in $2, and assign each item to $1

  3. #3
    Join Date
    May 2005
    Location
    Russia
    Beans
    537

    Re: bash: assinging array to a dynamic variable

    Well, I have this idea also, but how do I call $1 in such case?
    The constructs like
    Code:
    с=0
    for i in $2; do
      eval ${1[$c]}="'$i'"
      ((c++))
    done
    do not work...
    Last edited by PryGuy; August 31st, 2010 at 02:07 PM.

  4. #4
    Join Date
    May 2005
    Location
    Russia
    Beans
    537

    Re: bash: assinging array to a dynamic variable

    Wow! This worked!
    Code:
    getVar() {
      c=0
      for i in $2; do
        eval $1[$c]="'$i'"
        ((c++))
      done
    }
    
    getVar FOO "1 2 3 4 5"
    echo ${FOO[1]}
    exit 0

  5. #5
    Join Date
    Sep 2006
    Beans
    2,914

    Re: bash: assinging array to a dynamic variable

    Code:
    declare -a FOO=(1 2 3 4 5)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •