Find the answer to your Linux question:
Results 1 to 3 of 3
I'm hoping someone can explain this phenomenon for me. I have other options for the script where I was going to use this style. This is just curiosity. Creating an ...
  1. #1
    grg
    grg is offline
    Just Joined!
    Join Date
    Mar 2008
    Posts
    2

    [SOLVED] Bash script Array creation oddity

    I'm hoping someone can explain this phenomenon for me.

    I have other options for the script where I was going to use this style. This is just curiosity.

    Creating an array with a hand type list of [index]="item with spaces" works fine.

    Substituting a variable for the typed list produces a completely different result.

    Script:
    Code:
    #!/bin/bash
    
    dataString='[0]="one" [1]="two" [2]="three" [3]="four, only" [4]="five"'
    
    echo
    echo "manually creating dataArray"
    dataArray=( [0]="one" [1]="two" [2]="three" [3]="four, only" [4]="five"  )
    
    echo
    echo "ouputing dataArray:"
    for (( i = 0 ; i < ${#dataArray[@]} ; i++ )); do
      echo -e "\tdataArray[$i] = ${dataArray[i]}"
    done
    
    
    echo
    echo "creating dataArray2 from \$dataString=$dataString"
    dataArray2=( $dataString )
    
    echo
    echo "ouputing dataArray2:"
    for (( i = 0 ; i < ${#dataArray2[@]} ; i++ )); do
      echo -e "\tdataArray2[$i] = ${dataArray2[i]}"
    done
    Output:
    Code:
    manually creating dataArray
    
    ouputing dataArray:
            dataArray[0] = one
            dataArray[1] = two
            dataArray[2] = three
            dataArray[3] = four, only
            dataArray[4] = five
    
    creating dataArray2 from $dataString=[0]="one" [1]="two" [2]="three" [3]="four, only" [4]="five"
    
    ouputing dataArray2:
            dataArray2[0] = [0]="one"
            dataArray2[1] = [1]="two"
            dataArray2[2] = [2]="three"
            dataArray2[3] = [3]="four,
            dataArray2[4] = only"
            dataArray2[5] = [4]="five"
    Ideas?

  2. #2
    scm
    scm is offline
    Linux Engineer
    Join Date
    Feb 2005
    Posts
    1,044
    You need to let the shell evaluate, not just substitute, your "from-variable" assignment:
    Code:
    eval dataArray2=( $dataString )
    does the trick nicely.

  3. #3
    grg
    grg is offline
    Just Joined!
    Join Date
    Mar 2008
    Posts
    2

    Thanks

    Thank you, that will make for cleaner code than the alternatives.

    I feel a bit dense for not finding it, especially since I'd briefly pondered some sort of "Evaluate This" command.

Posting Permissions

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