posixKing
posixKing

Reputation: 418

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?

Upvotes: 1

Views: 3039

Answers (2)

redneb
redneb

Reputation: 23870

There is no reason to use an array slice here, just access the individual elements of the array. Try this:

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

In general you can access a single element of an array like that: ${array[3]}.

Note that in this case, it would have been preferable to do this:

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

Upvotes: 1

user8017719
user8017719

Reputation:

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

Upvotes: 4

Related Questions