1 #!/usr/bin/env bash
2 #
3 # Arrays decay upon assignment (without splicing) and equality. This will not
4 # be true in Oil -- arrays will be first class.
5
6 ### Assignment Causes Array Decay
7 set -- x y z
8 #argv "[$@]" # NOT DECAYED here.
9 var="[$@]"
10 argv.py "$var"
11 # stdout: ['[x y z]']
12
13 ### User arrays decay
14 declare -a a b
15 a=(x y z)
16 b="${a[@]}" # this collapses to a string
17 c=("${a[@]}") # this preserves the array
18 c[1]=YYY # mutate a copy -- doesn't affect the original
19 argv.py "${a[@]}" "${b[@]}" "${c[@]}"
20 # stdout: ['x', 'y', 'z', 'x y z', 'x', 'YYY', 'z']
21
22 ### $a gives first element of array
23 a=(1 '2 3')
24 echo $a
25 # stdout: 1
26
27 ### Assign to array index without initialization
28 a[5]=5
29 a[6]=6
30 echo "${a[@]}" ${#a[@]}
31 # stdout: 5 6 2
32
33 ### a[40] grows array
34 a=(1 2 3)
35 a[1]=5
36 a[40]=30 # out of order
37 a[10]=20
38 echo "${a[@]}" "${#a[@]}" # length is 1
39 # stdout: 1 5 3 20 30 5
40
41 ### array decays to string when comparing with [[ a = b ]]
42 a=('1 2' '3 4')
43 s='1 2 3 4' # length 2, length 4
44 echo ${#a[@]} ${#s}
45 [[ "${a[@]}" = "$s" ]] && echo EQUAL
46 # stdout-json: "2 7\nEQUAL\n"
47
48 ### Increment array variables
49 a=(1 2)
50 (( a++ )) # doesn't make sense
51 echo "${a[@]}"
52 # stdout: 2 2
53