lufork lufork - 2 months ago 5
Bash Question

How to use offset in arrays in bash?

Here is my code.

#! /bin/bash
array=(3 2 1 0 0 0 0 0 0 0)
for i in {0..10}
do
this=${array:$i:$((i+1))}
echo $this
done


I want to print each number of my number separately. I have used this line to get the array elements using an offset number.

this=${array:$i:$((i+1))}


However I am only getting 3 printed and rest all are new lines. I basically want to print 3, 2, 1 etc on separate lines. How do I correct this?

Answer

First, you need to use the whole array array[@], not array.

echo "${array[@]:3:2}"

Then, you may change the index to simple variable names:

this=${array[@]:i:i+1}

And then, you probably need to extract just one value of the list:

this=${array[@]:i:1}

Try this code:

array=(3 2 1 0 0 0 0 0 0 0)
for i in {0..10}
do
    this=${array[@]:i:1}
    echo "$this"
done
Comments