Bash Scripting Examples: Iteration and Arrays

Last updated:
Table of Contents

Create an array

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

Iterate through array

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

for i in "${some_array[@]}"; do
  echo $i
done

Iterate through a range

for i in {1..5}; do
  echo $i
done

Iterate through lines in a file

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

Iterate through files in a directory

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

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

Split a string into an array using a delimiter

I think IFS is needed even though you are not going to use it. (The string gets split into the tokens variable.)

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

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

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

Dialogue & Discussion