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
${arr[@]:1:3}slices by offset and length.- A negative offset counts from the end — note the space before it.
${arr[*]}joins on the first character ofIFS.
Keywords and builtins used here
echounset
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.
Step 3 of 3 in Arrays, step 12 of 26 in Language basics.