Home > bash > Bash Arrays – Dynamic indexes

Bash Arrays – Dynamic indexes

Problem:
Add items to an array without giving an index.

Solution:

#!/bin/bash
# Instead of this
#name_id[0]="Peter|487147"
#name_id[1]="Jane|5843695"
#name_id[2]="Sally|254148569"

# Use this
name_id[${#name_id[@]}]="Peter|487147"
name_id[${#name_id[@]}]="Jane|5843695"
name_id[${#name_id[@]}]="Sally|254148569"

for data in "${name_id[@]}"
do
    echo $data;
    name=$(echo $data | cut -d"|" -f1)
    id=$(echo $data | cut -d"|" -f2)
    echo $name
    echo $id
done

${#name_id[@]} — gives the total number of items in the array.

This means that in future if you would like to add an item after Peter, you would not need to change the array indexes for the remaining items.

Advertisements
Categories: bash Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: