Bash Scripting Examples: Iteration and Arrays

Last updated:
Table of Contents

Create an array


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

For i in range do

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

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"; 

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"

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"

echo $some_var
#prints "baz"

Dialogue & Discussion