27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

echo ${colors[$index]}<br />

let "index = $index + 1"<br />

done<br />

# Each array element listed on a separate line.<br />

# If this is not desired, use echo −n "${colors[$index]} "<br />

#<br />

# Doing it with a "for" loop instead:<br />

# for i in "${colors[@]}"<br />

# do<br />

# echo "$i"<br />

# done<br />

# (Thanks, S.C.)<br />

echo<br />

# Again, list all the elements in the array, but using a more elegant method.<br />

echo ${colors[@]}<br />

# echo ${colors[*]} also works.<br />

echo<br />

# The "unset" command deletes elements of an array, or entire array.<br />

unset colors[1]<br />

# Remove 2nd element of array.<br />

# Same effect as colors[1]=<br />

echo ${colors[@]}<br />

# List array again, missing 2nd element.<br />

unset colors<br />

echo; echo −n "Colors gone."<br />

echo ${colors[@]}<br />

exit 0<br />

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

# Delete entire array.<br />

# unset colors[*] and<br />

#+ unset colors[@] also work.<br />

# List array again, now empty.<br />

As seen in the previous example, either ${array_name[@]} or ${array_name[*]} refers to all the elements<br />

of the array. Similarly, to get a count of the number of elements in an array, use either ${#array_name[@]}<br />

or ${#array_name[*]}. ${#array_name} is the length (number of characters) of ${array_name[0]}, the first<br />

element of the array.<br />

Example 26−4. Of empty arrays and empty elements<br />

#!/bin/bash<br />

# empty−array.sh<br />

# Thanks to Stephane Chazelas for the original example,<br />

#+ and to Michael Zick for extending it.<br />

# An empty array is not the same as an array with empty elements.<br />

array0=( first second third )<br />

array1=( '' ) # "array1" has one empty element.<br />

array2=( ) # No elements... "array2" is empty.<br />

echo<br />

ListArray()<br />

{<br />

echo<br />

echo "Elements in array0: ${array0[@]}"<br />

echo "Elements in array1: ${array1[@]}"<br />

Chapter 26. Arrays 295

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!