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"

For each element in an array, do

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
Twitter Linkedin YC Hacker News Reddit

For i in range do

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

For i in sequence, do

The seq <from> <to> command generates a list of numbers.

for NUM in `seq 1 10`; do 
  ./some-command "$NUM"; 
done

For each line in a file, do

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

For each file in a 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 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