bash shell script declaring/creating arrays

Contributor Icon Contributed by qmchenry Date Icon August 30, 2004  
Tag Icon Tagged: Bourne shell scripting

The use of array variable structures can be invaluable. This recipe describes several methods for delcaring arrays in bash scripts.


The following are methods for declaring arrays:

names=( Jennifer Tonya Anna Sadie )

This creates an array called names with four elements (Jennifer, Tonya, Anna, and Sadie).

names=( "John Smith" "Jane Doe" )

This creates two array elements, each containing a space.

colors[0] = red
colors[3] = green
colors[4] = blue

This declares three elements of an array using nonsequential index values and creates a sparse array (there are no array elements for index values 1 or 2).

filearray=( `cat filename | tr '\n' ' '`)

This example places the contents of the file filename into an array. The tr command converts newlines to spaces so that multiline files will be handled properly.

names=( "${names[@]}” “Molly” )

This example adds another element to an existing array names.

If anyone has other techniques for creating or adding to arrays, add a comment to this recipe and share the wealth!

Previous recipe | Next recipe |
 
  • move all array
    here is another method to add elements to an array


    for foo in $(find -type f -iname "*.png" -printf "%fn"); do
    file[${#file[*]}]=$foo
    done



    will create an array of all png files
  • Barun
    Wow!!! The trick for initializing an array from a file is superb!
  • Punit
    Here is another method of adding elements in the array.. It works best with korn shell

    set -A array_example 1 2 3 4 5
    i=0
    echo ${array_example[$i]}
  • secoif
    One way to merge two arrays:

    #existing array
    existing=(item1, item2, item3);

    #items to merge (including an item requiring correct quoting)
    merge=(item4 item5 "${item6}*");

    count=${#existing[@]};
    num_new_items=${#merge[@]};
    # this loop appends items to the end of the array
    for (( i=0;i<$num_new_items;i++)); do
    echo ${i};
    existing[$count]=${merge[${i}]};
    let count+=1;
    done

    count=${#existing[@]}
    for (( i=0;i<$count;i++)); do
    echo ${existing[${i}]};
    done
  • Erik J
    Reading a line, while preseriving whitespaces seems har dto do from a file

    You can do it this way:
    <pre>
    cat $file | while read line; do
    echo "$line";
    done
    </pre>
  • bob.experience
    Well done man! Thanks for the tip!
  • Manav
    Good one
blog comments powered by Disqus