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.py "[$@]"
9 var="[$@]"
10 argv.py "$var"
11 ## STDOUT:
12 ['[x', 'y', 'z]']
13 ['[x y z]']
14 ## END
15
16 #### Array Decay with IFS
17 IFS=x
18 set -- x y z
19 var="[$@]"
20 argv.py "$var"
21 ## stdout: ['[x y z]']
22
23 #### User arrays decay
24 declare -a a b
25 a=(x y z)
26 b="${a[@]}" # this collapses to a string
27 c=("${a[@]}") # this preserves the array
28 c[1]=YYY # mutate a copy -- doesn't affect the original
29 argv.py "${a[@]}"
30 argv.py "${b}"
31 argv.py "${c[@]}"
32 ## STDOUT:
33 ['x', 'y', 'z']
34 ['x y z']
35 ['x', 'YYY', 'z']
36 ## END
37
38 #### $a gives first element of array (TODO: osh should disallow)
39 a=(1 '2 3')
40 echo $a
41 ## stdout: 1
42
43 #### Assign to array index without initialization
44 a[5]=5
45 a[6]=6
46 echo "${a[@]}" ${#a[@]}
47 ## stdout: 5 6 2
48
49 #### a[40] grows array
50 a=(1 2 3)
51 a[1]=5
52 a[40]=30 # out of order
53 a[10]=20
54 echo "${a[@]}" "${#a[@]}" # length is 1
55 ## stdout: 1 5 3 20 30 5
56
57 #### array decays to string when comparing with [[ a = b ]]
58 a=('1 2' '3 4')
59 s='1 2 3 4' # length 2, length 4
60 echo ${#a[@]} ${#s}
61 [[ "${a[@]}" = "$s" ]] && echo EQUAL
62 ## STDOUT:
63 2 7
64 EQUAL
65 ## END
66
67 #### ++ on a whole array increments the first element (disallowed in OSH)
68 a=(1 10)
69 (( a++ )) # doesn't make sense
70 echo "${a[@]}"
71 ## stdout: 2 10
72 ## OK osh status: 1
73 ## OK osh stdout-json: ""
74
75 #### Apply vectorized operations on ${a[*]}
76 a=('-x-' 'y-y' '-z-')
77
78 # This does the prefix stripping FIRST, and then it joins.
79 argv.py "${a[*]#-}"
80 ## STDOUT:
81 ['x- y-y z-']
82 ## END
83 ## N-I mksh status: 1
84 ## N-I mksh stdout-json: ""