| 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 | #### $array is not valid in OSH, is ${array[0]} in ksh/bash |
| 39 | a=(1 '2 3') |
| 40 | echo $a |
| 41 | ## STDOUT: |
| 42 | 1 |
| 43 | ## END |
| 44 | ## OK osh status: 1 |
| 45 | ## OK osh stdout-json: "" |
| 46 | |
| 47 | #### ${array} is not valid in OSH, is ${array[0]} in ksh/bash |
| 48 | a=(1 '2 3') |
| 49 | echo ${a} |
| 50 | ## STDOUT: |
| 51 | 1 |
| 52 | ## END |
| 53 | ## OK osh status: 1 |
| 54 | ## OK osh stdout-json: "" |
| 55 | |
| 56 | #### Assign to array index without initialization |
| 57 | a[5]=5 |
| 58 | a[6]=6 |
| 59 | echo "${a[@]}" ${#a[@]} |
| 60 | ## stdout: 5 6 2 |
| 61 | |
| 62 | #### a[40] grows array |
| 63 | a=(1 2 3) |
| 64 | a[1]=5 |
| 65 | a[40]=30 # out of order |
| 66 | a[10]=20 |
| 67 | echo "${a[@]}" "${#a[@]}" # length is 1 |
| 68 | ## stdout: 1 5 3 20 30 5 |
| 69 | |
| 70 | #### array decays to string when comparing with [[ a = b ]] |
| 71 | a=('1 2' '3 4') |
| 72 | s='1 2 3 4' # length 2, length 4 |
| 73 | echo ${#a[@]} ${#s} |
| 74 | [[ "${a[@]}" = "$s" ]] && echo EQUAL |
| 75 | ## STDOUT: |
| 76 | 2 7 |
| 77 | EQUAL |
| 78 | ## END |
| 79 | |
| 80 | #### ++ on a whole array increments the first element (disallowed in OSH) |
| 81 | a=(1 10) |
| 82 | (( a++ )) # doesn't make sense |
| 83 | echo "${a[@]}" |
| 84 | ## stdout: 2 10 |
| 85 | ## OK osh status: 1 |
| 86 | ## OK osh stdout-json: "" |
| 87 | |
| 88 | #### Apply vectorized operations on ${a[*]} |
| 89 | a=('-x-' 'y-y' '-z-') |
| 90 | |
| 91 | # This does the prefix stripping FIRST, and then it joins. |
| 92 | argv.py "${a[*]#-}" |
| 93 | ## STDOUT: |
| 94 | ['x- y-y z-'] |
| 95 | ## END |
| 96 | ## N-I mksh status: 1 |
| 97 | ## N-I mksh stdout-json: "" |