Home > database >  How to loop through a bash array, excluding certain initial elements?
How to loop through a bash array, excluding certain initial elements?

Time:10-01

If I have an array:

declare -a arr=("element1" "element2" "element3" "element4" "element5" "element6")

for i in "${arr[@]}"
do
   echo "$i"
done

and only wanted to loop through the element3 to element 6, how can I specify that? Generally, if I wanted to exclude the first k elements of an array, is there a way to subset that array?

CodePudding user response:

You can write:

for i in "${arr[@]:2}"

Per the bash man page, the general syntax is:

${parameter:offset}
${parameter:offset:length}

...If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${parameter[offset]}.

  • Related