1 #
2 # Arrays decay upon assignment (without splicing) and equality. This will not
3 # be true in Oil -- arrays will be first class.
4
5 #### Assignment Causes Array Decay
6 set -- x y z
7 argv.py "[$@]"
8 var="[$@]"
9 argv.py "$var"
10 ## STDOUT:
11 ['[x', 'y', 'z]']
12 ['[x y z]']
13 ## END
14
15 #### Array Decay with IFS
16 IFS=x
17 set -- x y z
18 var="[$@]"
19 argv.py "$var"
20 ## stdout: ['[x y z]']
21
22 #### User arrays decay
23 declare -a a b
24 a=(x y z)
25 b="${a[@]}" # this collapses to a string
26 c=("${a[@]}") # this preserves the array
27 c[1]=YYY # mutate a copy -- doesn't affect the original
28 argv.py "${a[@]}"
29 argv.py "${b}"
30 argv.py "${c[@]}"
31 ## STDOUT:
32 ['x', 'y', 'z']
33 ['x y z']
34 ['x', 'YYY', 'z']
35 ## END
36
37 #### strict_array: $array is not valid in OSH, is ${array[0]} in ksh/bash
38 shopt -s strict_array
39
40 a=(1 '2 3')
41 echo $a
42 ## STDOUT:
43 1
44 ## END
45 ## OK osh status: 1
46 ## OK osh stdout-json: ""
47
48 #### strict_array: ${array} is not valid in OSH, is ${array[0]} in ksh/bash
49 shopt -s strict_array
50
51 a=(1 '2 3')
52 echo ${a}
53 ## STDOUT:
54 1
55 ## END
56 ## OK osh status: 1
57 ## OK osh stdout-json: ""
58
59 #### Assign to array index without initialization
60 a[5]=5
61 a[6]=6
62 echo "${a[@]}" ${#a[@]}
63 ## stdout: 5 6 2
64
65 #### a[40] grows array
66 a=(1 2 3)
67 a[1]=5
68 a[40]=30 # out of order
69 a[10]=20
70 echo "${a[@]}" "${#a[@]}" # length is 1
71 ## stdout: 1 5 3 20 30 5
72
73 #### array decays to string when comparing with [[ a = b ]]
74 a=('1 2' '3 4')
75 s='1 2 3 4' # length 2, length 4
76 echo ${#a[@]} ${#s}
77 [[ "${a[@]}" = "$s" ]] && echo EQUAL
78 ## STDOUT:
79 2 7
80 EQUAL
81 ## END
82
83 #### ++ on a whole array increments the first element (disallowed with strict_array)
84 shopt -s strict_array
85
86 a=(1 10)
87 (( a++ )) # doesn't make sense
88 echo "${a[@]}"
89 ## stdout: 2 10
90 ## OK osh status: 1
91 ## OK osh stdout-json: ""
92
93 #### Apply vectorized operations on ${a[*]}
94 a=('-x-' 'y-y' '-z-')
95
96 # This does the prefix stripping FIRST, and then it joins.
97 argv.py "${a[*]#-}"
98 ## STDOUT:
99 ['x- y-y z-']
100 ## END
101 ## N-I mksh status: 1
102 ## N-I mksh stdout-json: ""