Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
syntax:arrays [2018/04/20 04:10]
tomroche add link to NAMES ADT declaration
syntax:arrays [2018/08/22 06:51] (current)
ebersphi
Line 152: Line 152:
 The method above, walking through an array by just knowing its number of elements, only works for arrays where all elements are set, of course. If one element in the middle is removed, then the calculation is nonsense, because the number of elements doesn'​t correspond to the highest used index anymore (we call them "//​sparse arrays//"​). The method above, walking through an array by just knowing its number of elements, only works for arrays where all elements are set, of course. If one element in the middle is removed, then the calculation is nonsense, because the number of elements doesn'​t correspond to the highest used index anymore (we call them "//​sparse arrays//"​).
  
 +Now, suppose that you want to replace your array ''​sentence''​ with the values in the [[#​purpose|previously-declared array]] ''​NAMES''​ . You might think you could just do
 +
 +<​code>​
 +$ unset sentence ; declare -a sentence=NAMES
 +$ echo ${#​sentence[@]}
 +1
 +# omit calculating max_index as above, and iterate as one-liner
 +$ for ((i = 0; i < ${#​sentence[@]};​ i++)); do  echo "​Element $i: '​${sentence[i]}'"​ ; done
 +Element 0: '​NAMES'​
 +</​code>​
 +
 +Obviously that's wrong. What about
 +
 +<​code>​
 +$ unset sentence ; declare -a sentence=${NAMES}
 +</​code>​
 +
 +? Again, wrong:
 +
 +<​code>​
 +$ echo ${#​sentence[*]}
 +1
 +$ for ((i = 0; i < ${#​sentence[@]};​ i++)); do  echo "​Element $i: '​${sentence[i]}'"​ ; done
 +Element 0: '​Peter'​
 +</​code>​
 +
 +So what's the **right** way? The (slightly ugly) answer is, reuse the enumeration syntax:
 +
 +<​code>​
 +$ unset sentence ; declare -a sentence=("​${NAMES[@]}"​)
 +$ echo ${#​sentence[@]}
 +4
 +$ for ((i = 0; i < ${#​sentence[@]};​ i++)); do  echo "​Element $i: '​${sentence[i]}'"​ ; done
 +Element 0: '​Peter'​
 +Element 1: '​Anna'​
 +Element 2: '​Greg'​
 +Element 3: '​Jan'​
 +</​code>​
  
 ==== Associative (Bash 4) ==== ==== Associative (Bash 4) ====
Line 355: Line 393:
 $ set -x; foo=bar declare arr=( {1..10} ) $ set -x; foo=bar declare arr=( {1..10} )
 + foo=bar + foo=bar
-+ declare 'a=(1)' 'a=(2)' 'a=(3)' 'a=(4)' 'a=(5)'++ declare 'arr=(1)' 'arr=(2)' 'arr=(3)' 'arr=(4)' 'arr=(5)' '​arr=(6)'​ '​arr=(7)'​ '​arr=(8)'​ '​arr=(9)'​ '​arr=(10)'
  
 $ touch xy=foo $ touch xy=foo
 ++ touch xy=foo
 $ declare x[y]=* $ declare x[y]=*
 + declare '​x[y]=*'​ + declare '​x[y]=*'​
  • syntax/arrays.1524197411.txt
  • Last modified: 2018/04/20 04:10
  • by tomroche