Array Variables

The [] syntax in Ion denotes that the contents within should be parsed as an array expression. On using let keyword for array variables, all array arguments must be wrapped within the [] syntax. Otherwise it will be coerced into a space-separated string. This design decision was made due to the possibility of an expanded array with one element being interpreted as a string.

Once created, you may call an array variable in the same manner as a string variable, but you must use the @ sigil instead of $. When expanded, arrays will be expanded into multiple arguments. Hence it is possible to use arrays to set multiple arguments in commands.

NOTE If an array is double quoted, it will be coerced into a string. This behavior is equivalent to invoking the $join(array) method.

NOTE: Brace expansions also create arrays.

Create a new array

Arguments enclosed within brackets are treated as elements within an array.

let array = [ one two 'three four' ]

Indexing into an array

Values can be fetched from an array via their position in the array as the index.

let array = [ 1 2 3 4 5 ]
echo @array[0]
echo @array[2..=4]
3 4 5

Copy array into a new array

Passing an array within brackets enables performing a deep copy of that array.

let array = [ 1 2 3 ]
let array_copy = [ @array ]
echo @array_copy
1 2 3

Array join

This will join each element of the array into a string, adding spaces between each element.

let array = [ hello world ]
let other_array = [ this is the ion ]
let array = [ @array @other_array shell ]
let as_string = @array
echo @array
echo $as_string
hello world this is the ion shell
hello world this is the ion shell

Array concatenation and variable stripping

The ++= and ::= operators can be used to efficiently concatenate an array in-place.

let array = [2 3]
let array ++= [4 5] # append
let array ::= [0 1] # append before beginning [0 1]
let array \\= [2 3] # remove variables 2 and 3
echo @array
let array ++= 6 # same with single variables
let array ::= -1
let array \\= 0
echo @array
0 1 4 5
-1 1 4 5 6

Practical array usage

Passing arrays as command arguments and capturing output of commands as arrays is useful.

mkdir -p _tmp _tmp/t1 _tmp/t2
cd _tmp
let args = [-a --file-type]
ls @args      # use args as arguments for command ls
let res = [ @(ls) ] # get result of ls as array res
echo @res     # output the array res
cd ..
rm -fr _tmp
t1 t2