Bash Scripting for Beginners (Part 2 — Arrays and Loops)
In this article, I will continue with arrays and loops.
Arrays
Shell supports a different type of variable called array. You can think of an array is a variable that can store multiple variables within it.
The Bash array variables come in two flavors, the one-dimensional indexed arrays(bash arrays), and the associative arrays. The indexed arrays are sometimes called lists and the associative arrays are sometimes called dictionaries or hash tables.*
One-dimensional indexed arrays are referenced using integers, and associative are referenced using strings.
Define a bash array
You have two ways to create a new array. The first one is to declare
command with -a
option to define an array.
$ declare -a test_array
Or, you can simply create Array by assigning elements.
$ test_array=("one" "two" "three")
In this example, all the elements are strings, but it need not be the case — arrays in Bash can contain both numbers and strings, e.g., myArray=(1 2 "three" 4 "five")
is a valid expression.
Define an associative array
You can define an associative array with declare
command with -A
option.
$ declare -A test_array
You can also create an associative array using the form below:
$ declare -A array_name
$ array_name=(
[index_1]=value_1
[index_2]=value_2
[index_3]=value_3
)
Adding New Elements to Array
You can append one or more elements to an existing array using (+=) operator.
test_array+=("four" "five")
Accessing array elements
Similar to other programming languages. Index number starts from 0.
$ echo ${test_array[0]}
one
The index of -1
references the last element.
$ echo ${test_array[-1]}
five
Note: So you will notice that when you reference an array, you do so with the syntax ${test_array}
, but when you reference a variable, you simply use a dollar sign: $i
.
Updating an array element
To update an array element, assign new value to the existing array by the index.
$ test_array[0]="zero"
$ echo ${test_array[0]}
zero
Deleting an array element
You can remove an array element by using the index number.
$ unset test_array[0]
Printing all elements of an array
If you use @
or *
as an index, the word expands to all members of the array.
The only difference between @
and *
is when the form ${test_array[x]}
is surrounded with double-quotes. In this case, *
expands to a single word where array elements are separated with space. @
expands each array element to a separate word. This is especially important when using the form to illiterate through array elements.
$ echo "${test_array[@]}"
zero two three four five
To print the keys of the array add the !
operator before the array name:
$ echo "${!test_array[@]}"
0 1 2 3 4
Array Length
To get the length of an array:
$ echo "${#test_array[@]}"
4
Loops
A loop enables you to execute a set of commands repeatedly. They are useful for automating repetitive tasks. There are 3 loop structures: while, until and for.
While loop
While loop executes the given commands until the given condition remains true. While loop usually uses with if statement. We will discuss it later.
Format:
while [ <some test> ]
do
<commands>
done
Example:
#!/bin/bashcounter=1
while [ $counter -le 10 ]
do
echo $counter
((counter++))
done
Output:
$ ./while_loop.sh
1
2
3
4
5
6
7
8
9
10
Until loop
Until loop executes until a given condition becomes true.
Format:
until [ <some test> ]
do
<commands>
done
Example:
#!/bin/bashcounter=1
until [ $counter -gt 10 ]
do
echo $counter
((counter++))
done
The syntax is almost exactly the same as the while loop. Sometimes, it just makes it a little easier to read if we phrase it with until rather than while.
For loop
There are a couple of ways to use for loops depending on the use case.
A simple for loop:
#!/bin/usr/env bash
for n in a b c;
do
echo $n
done
Output:
a
b
c
Range-based for loop:
In the example below, the loop starts from 1 to 10 and it is incremented by 2.
#!/bin/usr/env bash
for n in {1..10..2};
do
echo $n
done
Output:
1
3
5
7
9
If you don’t specify increment option, the loop increments by 1.
Example:
#!/bin/usr/env bash
for n in {1..5};
do
echo $n
done
Output:
1
2
3
4
5
Loop over array elements:
You can also use the for
loop to iterate over an array of elements.
Example
#!/bin/usr/env bash
name=("Ahmet" "Okan" "YILMAZ")
for i in ${name[@]};
do
echo $i
done
Output:
Ahmet
Okan
YILMAZ
The C-style for loop:
The syntax of the C-style for
loop is:
for ((INITIALIZATION; TEST; STEP))
do
[COMMANDS]
done
The INITIALIZATION
part is executed only once when the loop starts. Then, the TEST
part is evaluated. If it is false, the loop is terminated. If the TEST
is true, commands inside the body of the for
loop are executed, and the STEP
part is updated.
Example:
for ((i = 0 ; i <= 5; i++)); do
echo "Counter: $i"
done
Output:
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Loop Control
The break Statement: The break statement is used to terminate the execution of the entire loop.
Example:
#!/bin/shfor name in Ahmet Okan Selim YILMAZ; do
if [[ "$name" == 'Selim' ]]; then
break
fi
echo "$name"
done
Output:
Ahmet
Okan
The continue Statement: The continue statement is similar to the break command, except that it causes the current iteration of the loop to exit, rather than the entire loop.
Example:
#!/bin/shfor name in Ahmet Okan Selim YILMAZ; do
if [[ "$name" == 'Selim' ]]; then
continue
fi
echo "$name"
done
Output:
Ahmet
Okan
YILMAZ
We will continue in the next article.