bash shell script declaring/creating arrays

Contributor Icon Contributed by qmchenry  
Tag Icon Tagged: Bourne shell scripting  

The use of array variable structures can be invaluable. This recipe describes several methods for declaring 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!

 

14 Comments -


  1. Barun said on December 8, 2008

    Wow!!! The trick for initializing an array from a file is superb!

  2. Punit said on December 16, 2008

    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]}

  3. secoif said on January 22, 2009

    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

  4. Erik J said on January 29, 2009

    Reading a line, while preseriving whitespaces seems har dto do from a file

    You can do it this way:

    cat $file | while read line; do
    echo “$line”;
    done

  5. Manav said on April 13, 2009

    Good one

  6. bob.experience said on April 28, 2009

    Well done man! Thanks for the tip!

  7. asd said on November 11, 2009

    asdasdasd

  8. Aparnacomp said on July 12, 2010

    to convert a decimal number into its equivalent binary number…..using shell script:

    created by APARNA……….

    program

    echo ” program to convert a decimal number into its equivalent binary number…….”
    echo -e “enter a decimal number….”
    read no
    d=$no
    echo “____________________________________________________________”
    r=0
    b=0
    if test $d -eq 0
    then
    echo “Binary of 0 is 0…”
    else
    if test $d -eq 1
    then
    echo “Binary of 1 is 1…”
    else
    i=0
    echo “d=$d”
    while [ $d -ne 1 ]
    do
    r=`expr $d % 2`
    d=`expr $d / 2`
    echo ” r=$r”
    echo “d=$d”
    #add one by one element in an array………
    a=( “${a[@]}” “$r” )
    i=$i+1
    done
    a=( “${a[@]}” “$d” )
    fi
    fi
    echo “___________________________________________________________”
    len=${#a[*]}
    echo “equivalent binary number of $no is…..”
    j=-1
    l=`expr $len – 1`
    while [ $l -gt $j ]; do
    printf “%2d” ${a[$l]}
    let l–
    done
    printf “n”
    echo ” GOOD BYE……….”

  9. Ll said on July 28, 2010

    did u create it.. wow….

  10. Ayesha said on August 3, 2010

    How can I insert elements in an array from another text file?? I want to read numbers from another text file and insert them in an array??

  11. Bill Hernandez said on August 18, 2010

    As I was digging through my notes I found this…

    ——————————————————
    NOTES : Sample code for [ jot ] command…
    ——————————————————

    # +———+———+———+———+———+———+———+———+———+
    RANDOM NUMBERS – print three random numbers between [1 - 500]
    [2007.06.08](06:26AM) -> [bhernandez] ~
    $ operation=-r ; reps=3 ; begin=1 ; end=500 ; jot $operation $reps $begin $end

    15
    438
    164
    # +———+———+———+———+———+———+———+———+———+

    SEQUENCE OF NUMBERS

    jot 21 -1 1.00 # prints 21 evenly spaced numbers increasing from -1 to 1.

    jot 20 5 # prints 20 evenly spaced numbers starting at 5

    my_seq=`jot 20 1` # prints 20 evenly spaced numbers starting at 1
    echo ${my_seq}

    # +———+———+———+———+———+———+———+———+———+
    # ROUTINE FROM bh_dir_samples – Example using {sed, wc, jot, and a for loop}
    # FOR MORE EXAMPLES SEE –> bh_dir_samples
    # +———+———+———+———+———+———+———+———+———+
    echo
    echo “( 19 ) BASH – Example using {sed, wc, jot, and a for loop}”
    my_path=”/tmp/state/city/farm/barn/tractor/keys/red/small”
    my_str=`echo “$my_path” | sed ’s/// /g’`
    my_word_count=`echo $my_str | wc -w` ;
    how_many_levels_back=2
    max_count=`expr $my_word_count – $how_many_levels_back`
    my_seq=`jot $max_count 1` # prints 20 evenly spaced numbers starting at 1

    n=1
    for arg in $my_str ;
    do
    if [ $n -gt 0 ]
    then
    if [ $n -le $max_count ]
    then
    # echo -n “$n/$arg”
    # echo -n “/$arg”
    my_result=”${my_result}/${arg}”
    fi
    fi
    let “n++”
    done

    echo “( a ) –> $my_path = $my_path”
    echo “( b ) –> $how_many_levels_back = $how_many_levels_back”
    echo “( c ) –> $max_count = $max_count”
    echo “( d ) –> $my_seq = `echo $my_seq`” # ( d ) This one shows up on one line
    echo “( e ) –> $my_seq = ${my_seq}” # ( e ) This shows up on separate lines
    echo “( f ) –> $my_seq = `echo $my_seq | sed ’s/n/ /g’`” # ( f ) This one shows up on one line
    echo “( g ) –> $my_result = $my_result”

    exit
    # +———+———+———+———+———+———+———+———+———+
    # RESULTS
    # +———+———+———+———+———+———+———+———+———+
    ( 19 ) BASH – Example using {sed, wc, jot, and a for loop}
    ( a ) –> $my_path = /tmp/state/city/farm/barn/tractor/keys/red/small
    ( b ) –> $how_many_levels_back = 2
    ( c ) –> $max_count = 7
    ( d ) –> $my_seq = 1 2 3 4 5 6 7
    ( e ) –> $my_seq = 1
    2
    3
    4
    5
    6
    7
    ( f ) –> $my_seq = 1 2 3 4 5 6 7
    ( g ) –> $my_result = /tmp/state/city/farm/barn/tractor/keys

    # +———+———+———+———+———+———+———+———+———+
    [2007.05.08](04:40PM) -> [bhernandez] ~
    $
    # +———+———+———+———+———+———+———+———+———+

  12. Varun Avashia said on September 14, 2010

    #Initialize commands
    init command

    echo “Total packages found: ” $(rpm -qa | grep -c “some string”)

    #Search for packages and remove them one by one
    for package in $(rpm -qa | grep “some string”);
    do
    echo “Removing ” $package
    rpm -fe $package
    done

    #Cleanup
    Clean up commands

    echo “Remaining packages: ” $(rpm -qa | grep -c “some string”)

  13. Matt Duffy said on September 22, 2010

    Hi, just found this site and it’s been really helpful so far. I have a problem with assigning the output of a find command into an array. The find command works fine on it’s own:

    find “$path” ( -type d -o -type f ) -name ‘[.]*’ -print0

    where $path is a string with a file system path. This finds all files or directories in a subtree with names that begin with a dot (.svn, .DS_Store, etc). Currently, the output is piped to xargs to delete the files it finds. It uses the -print0 to account for space characters in $path.

    What I would like to do is have the output redirected into an array where each array element is a string path value for a file/directory with a dot name. The problem I am having is that there are many files the subtree that have spaces in their name and when the find command output is redirected to the array the space characters in the string cause it to be split into more than one array element.

    For example, a string like:
    web/Cappuccino/iTunes Layout/Frameworks/AppKit/Resources/.DS_Store

    will be split at iTunesLayout to create array elements

    array[n] = web/Cappuccino/iTunes
    array[n+1] = Layout/Frameworks/AppKit/Resources/.DS_Store

    I have tried a number of different syntaxes all with the same result. I feel like it’s just a simple error in my variable quoting or something, but I am stuck. I think it should look something like this (but this is wrong):

    array=( `find “$path” ( -type f -or -type d ) -name ‘[.]*’ -print0 | xargs -0 -n 1` )

    Any suggestions? I am really stuck on this.

    Cheers

  14. Bf Hayati said on July 1, 2011

    thats great but can any one know how to use array in loop like ,or know how to change number from decimle into binary  plzzzzzzzzzzzzz

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -