< Day Day Up > |
Versions of bash 2.x provide for creation of one-dimensional arrays. Arrays allow you to collect a list of words into one variable name , such as a list of numbers , a list of names , or a list of files. Arrays are created with the built-in function declare “a , or can be created on the fly by giving a subscript to a variable name, such as x[0]=5 . The index value is an integer starting at 0. There is no maximum size limit on the array, and indices do not have to be ordered numbers, such as, x[0] , x[1] , x[2] , and so on. To extract an element of an array, the syntax is ${arrayname[index]} . If declare is given the “a and “r options, a read-only array is created. FORMAT declare -a variable_name variable = ( item1 item2 item3 ... ) Example 13.78.declare -a nums=(45 33 100 65) declare -ar names (array is readonly) names=( Tom Dick Harry) states=( ME [3]=CA CT ) x[0]=55 n[4]=100 When assigning values to an array, they are automatically started at index 0 and incremented by 1 for each additional element added. You do not have to provide indices in an assignment, and if you do, they do not have to be in order. To unset an array, use the unset command followed by the array name, and to unset one element of the array, use unset and the arrayname[subscript] syntax. The declare , local , and read-only built-ins also can take the “a option to declare an array. The read command with the “a option is used to read in a list of words from standard input into array elements. Example 13.79.1 $ declare -a friends 2 $ friends=(Sheryl Peter Louise) 3 $ echo ${friends[0]} Sheryl 4 $ echo ${friends[1]} Peter 5 $ echo ${friends[2]} Louise 6 $ echo " All the friends are ${friends[*]}" All the friends are Sheryl Peter Louise 7 $ echo "The number of elements in the array is ${#friends[*]}" The number of elements in the array is 3 8 $ unset friends or unset ${friends[*]} EXPLANATION
Example 13.80.1 $ x[3]=100 $ echo ${x[*]} 100 2 $ echo ${x[0]} 3 $ echo ${x[3]} 100 4 $ states=(ME [3]=CA [2]=CT) $ echo ${states[*]} ME CA CT 5 $ echo ${states[0]} ME 6 $ echo ${states[1]} 7 $ echo ${states[2]} CT 8 $ echo ${states[3]} CA EXPLANATION
|
< Day Day Up > |