Arrays
References
Arrays
- Can be indexed or associative
- Indexes start at 0
- Indexes can be any arithmetic expression that evaluates to 0 or a positive number
- Indexes need not be contiguous
- Unassigned elements do not exist
- Elements can contain strings or numbers
- Any string operation using the ${name ... } notation can be applied to all string elements
Creating an empty array (Optional for indexed array)
declare -a my_array # Indexed array (Starting with Bash 2.0)
declare -A my_array # Associative array (Starting with Bash 4.0)
Declaring an array and making an initial assignment in one step
declare -a my_array=Fred # assignes to ${my_array[0]}
declare -a my_array=(Fred Wilma Pebbles Barney Betty Bamm-bamm)
declare -a my_array=([3]=Barney [0]=Fred [4]=Betty)
declare -A music[genre]=rock
declare -A music=([genre]=rock [tempo]=fast)
Assigning values to an indexed array
my_array[2]=alice
my_array[0]=hatter
my_array[1]=dutchess
my_array=([2]=alice [0]=hatter [1]=duchess)
my_array=(hatter duchess alice)
my_array=(hatter [5]duchess alice) # Assigns hatter to element 0, duchess to 5 and alice to 6)
Assigning values to an associative array
my_array[John]=321-9876
my_array[Bill]=123-6789
my_array=([Alice]=234-5678 [Mary]=765-4321) # Compound array statement replaces the old array with a new one
Appending to an array
a=(cat) # $a{[0]} is cat
a=(${a[@]} dog) # $a{[1]} is dog
# or
a[${#now[*]}]="dog"
a[3]=rat
a+=(mouse horse fox) # a now has 6 elements
music+=([volume]=loud)
Querying an array
echo ${my_array[@]} # list the values
echo ${!my_array[@]} # list the keys
echo ${#my_array[@]} # number of elements
echo ${my_array[*]} # alternate syntax for any of the above
echo ${#my_array[2]} # length of the third element
echo ${my_arrayZ[@]:1} # all elements following element[0]
echo ${my_arrayZ[@]:1:2} # only the next two elements following element[0]
Building an array of sentences
$ cat now
Now is the time
For all good men
To go to the aid
Of their country
$ while read line;do
> now=("${now[@]}" "$line")
> done < <(cat now)
$ echo ${now[0]}
Now is the time
$ echo ${now[1]}
For all good men
$
Building an array of directory entries
declare -a devices=( /dev/* )
Send mail to the Webmaster
 |
This site best viewed with a browser |
| Warning: This is a Debian centric site and MAY contain peanuts. |
| Many thanks to Debra Lynn and Ian Murdock for making Debian possible |
| First created Apr 22, 2008 ~ Last revised October 17, 2011 |