Print array elements from index k
I have a bash array and want to print the array elements starting from index k
.
Things did not work out with the following strategy.
printf "%s\n" "${ar[$j:]}"
The syntax is ${ar[@]:j}
1. From the Parameter Expansion
section of man bash
:
${parameter:offset:length}
.
.
.
If parameter is an indexed array name subscripted by @ or *, the
result is the length members of the array beginning with ${pa‐
rameter[offset]}. A negative offset is taken relative to one
greater than the maximum index of the specified array. It is an
expansion error if length evaluates to a number less than zero.
So given
$ ar=("1" "2 3" "4" "5 6" "7 8" "9")
then (remembering that bash array indixing is 0-based):
$ j=3; printf '%s\n' "${ar[@]:j}"
5 6
7 8
9
Alternatively, use a C-style for loop:
for ((i=k;i<${#ar[@]};i++)); do
printf '%s\n' "${ar[i]}"
done
- or
${ar[@]:$j}
if you prefer - the second$
is optional, since the indices are evaluated in a numerical context similar to((...))