LDP/LDP/guide/docbook/abs-guide/array-ops.sh

48 lines
1.6 KiB
Bash
Raw Normal View History

2003-11-03 16:26:45 +00:00
#!/bin/bash
# array-ops.sh: More fun with arrays.
array=( zero one two three four five )
2004-02-16 17:21:02 +00:00
# Element 0 1 2 3 4 5
2003-11-03 16:26:45 +00:00
echo ${array[0]} # zero
echo ${array:0} # zero
# Parameter expansion of first element,
#+ starting at position # 0 (1st character).
echo ${array:1} # ero
# Parameter expansion of first element,
#+ starting at position # 1 (2nd character).
echo "--------------"
echo ${#array[0]} # 4
# Length of first element of array.
echo ${#array} # 4
# Length of first element of array.
# (Alternate notation)
2004-02-16 17:21:02 +00:00
echo ${#array[1]} # 3
2003-11-03 16:26:45 +00:00
# Length of second element of array.
2004-02-16 17:21:02 +00:00
# Arrays in Bash have zero-based indexing.
2003-11-03 16:26:45 +00:00
echo ${#array[*]} # 6
# Number of elements in array.
echo ${#array[@]} # 6
# Number of elements in array.
echo "--------------"
array2=( [0]="first element" [1]="second element" [3]="fourth element" )
2008-11-23 22:43:47 +00:00
# ^ ^ ^ ^ ^ ^ ^ ^ ^
# Quoting permits embedding whitespace within individual array elements.
2003-11-03 16:26:45 +00:00
echo ${array2[0]} # first element
echo ${array2[1]} # second element
echo ${array2[2]} #
# Skipped in initialization, and therefore null.
echo ${array2[3]} # fourth element
2008-11-23 22:43:47 +00:00
echo ${#array2[0]} # 13 (length of first element)
echo ${#array2[*]} # 3 (number of elements in array)
2003-11-03 16:26:45 +00:00
2008-11-23 22:43:47 +00:00
exit