Bash Scripting Examples: Iteration and Arrays

Bash Scripting Examples: Iteration and Arrays

Last updated:
Table of Contents

Create array

some_array[0]="foo"
some_array[1]="bar"
some_array[2]="baz"

For element in array, do

Suppose some_array is an array like the one in the previous example. This will print the array's contents.

# create array
some_array[0]="foo"
some_array[1]="bar"
some_array[2]="baz"

for i in "${some_array[@]}"; do
  echo "$i";
done
# PRINTS
# foo
# bar
# bar

For i in range, do

for i in {1..5}; do
  echo "$i";
done
# PRINTS
# 1
# 2
# 3
# 4
# 5

For i in sequence, do

seq <from> <to> command generates a list of numbers from <from> to to:

for NUM in `seq 1 4`; do 
  ./some-command "$NUM"; 
done
# PRINTS
# 1
# 2
# 3
# 4

For element in sequence do

The elements in the arbitrary list can be of mixed types

For cases when you want to run some commands for every element in an arbitrary list:

Example For each element in the list [1, 3, "foo"] run echo:

for i in 1 3 "foo"; do
  echo "$i"
done
# PRINTS
# 1
# 3 
# foo

For element in sequence do, one-liner

Semicolons (;) are now mandatory to separate commands

Same as above, but as a single line so you can run in the terminal:

$ for i in 1 3 "foo"; do echo "$i"; done;
1
3
foo

For line in file, do

while read p; do
  echo $p
done < /path/to/some/file

For file in directory, do

as a one-liner: for f in some/path/*; do echo "$f"; done

for f in some/path/*; do
  echo "$f"
done 

Split string by delimiter

IFS is needed even though you are not going to use it.

The string gets split into the tokens array variable.

IFS=':' read -a tokens <<< "foo:bar:baz"

echo ${tokens[0]}
#prints "foo"

some_var=${tokens[2]}
echo $some_var
#prints "baz"