typestar

Array slicing in Bash

Slices, joins and indices from the expansion syntax.

week=(mon tue wed thu fri sat sun)

# ${arr[@]:start:length} slices; negative start counts from the end
echo "${week[@]:1:3}"
echo "${week[@]: -2}"

# joined into one string with the first character of IFS
IFS=,
echo "as csv: ${week[*]}"
unset IFS

echo "indices: ${!week[*]}"

How it works

  1. ${arr[@]:1:3} slices by offset and length.
  2. A negative offset counts from the end — note the space before it.
  3. ${arr[*]} joins on the first character of IFS.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
276
Tokens
53
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 45 seconds.

Type this snippet

Step 3 of 3 in Arrays, step 12 of 26 in Language basics.

← Previous Next →