Shell - Array and Loop

Array Operations

Indexing

Shell array uses 0-based indexing.

Basically, shell array indexing follows the syntax:

syntax
1
2
${A[I]} # index a single element
${A[@]:I:N} # take a slice with N elements, starting from I-th element

Let’s take a look at a few pratical use cases.

example
1
2
3
4
5
6
7
A=(a b c)
echo ${A[0]} # index 0-th element
echo ${A[@]} # chain all elements
echo ${A[@]:1:2} # slice 2 elements from the 1st element. output: b c
echo ${A[@]:1:1} # equivalent to ${A[1]}
echo ${A[@]:1} # slice from 1st element till the end of array, output: b c
echo ${A[@]: -2:1} # negative indexing , note that _a space right before -2_ is necessary. output: b

Concatenation

example
1
B=(${A[@]} x)

Loop

Iterate over a range

Python range style iteration is supported since bash version 3.0.

syntax
1
2
3
4
for i in {START..END}
do
echo $i
done

Bash 4.0+ has builtin support for setting up a step value:

syntax
1
2
3
4
for i in {START..END..STEP}
do
echo $i
done

Expression based iteration

example
1
2
3
4
for (( c=1; c<10; c++ ))
do
echo $c
done

An infinite loop

example
1
2
3
4
for (( ; ; ))
do
# do staff
done