01. For loops for, in, do, done

Loops are used to execute the a statement of tasks a repeated number of times or until a condition is met. There are two types of loops used in shell scripting - the for and while loops. Let's start with the for loop, which can take on a variety of tasks.

Keywords

The keywords used in a for-loop are for, in, do, and done. Here is the structure for a for-loop.

for variableName in list
do
  some commands
done     

1) Iterate through a list

One way to run through a for loop is to iterate through a list. This list may consist of strings or numbers.

#!/bin/bash
 
for food in "bbq" "french fries" "coleslaw"
do
  echo "I like $food."
done
p
  | Here's the output:
pre
  code.lang-bash
$ ./test
I like bbq.
I like french fries.
I like coleslaw.

Remember that with brace expansions, you can list a range of numbers or letters.

#!/bin/bash
 
printf "Press enter to launch rocket ship: "
read
 
for num in {5..1}
do 
  echo "$num..."
  sleep 1
done
 
for rocket in 'Blastoff!' '    A    ' '   / \   ' '       | |=|   ' '   | |   ' '   | |   ' '  _|=|_  ' ' / | | \ '     | ' | \,/ | ' ' |/" "\| ' ' """"""" '
do
  echo "$rocket"
  sleep 1
done

Try copying and pasting this code snippet and running it to see a rocketship blast off!

2) Repeat per output of a command

You may also loop through outputs of a command.

#!/bin/bash
 
count=1
for output in $(ls)
do 
  printf "File %2d: %s\n" $count $output
  ((count=count+1))
done

This script simply takes the output of an ls command and lists them in order with an integer marking its position.

$ ./test
File  1: Applications
File  2: Desktop
File  3: Documents
File  4: Downloads
File  5: Dropbox
File  6: Library
File  7: Movies
File  8: Music
File  9: Pictures
File 10: Public

3) Three-step for loops

In most programming language, there are three-step for loops. The first expression is the variable declaration, the second is the loop condition test and the third is some evaluation that updates the expression.

To use such a three-step for loop in shell scripting, use the following syntax:

#!/bin/bash
for (( i=1; i <= 5; i++ ))
do
  echo "$i Mississippi..."
  sleep 1
done
 
echo "Ready or not here I come!"

The result is simply:

$ ./test
1 Mississippi...
2 Mississippi...
3 Mississippi...
4 Mississippi...
5 Mississippi...
Ready or not here I come!

To get an inifinite loops, simply omit all three placeholders.

#!/bin/bash
for (( ; ; ))
do
  echo "ctrl+c to stop this runaway infinite loop!"
done

4) Looping over command line arguments

If you remember from our previous tutorial, the $@ variable stores all command line arguments. We can thus use the $@ as a list and loop over our arguments.

However, placing the $@ is optional. By default, the in $@ is already included.

#!/bin/bash
for i 
do
  case $i in
  -v) 
    verbose=1
    quiet=
    ;;
  -q) 
    quiet=1
    verbose=
    ;;
  esac
done

5) Looping specific files within directory

We can also use a for loop to iterate through items of a directory. Here, we take all text files within the current directory and stitch them together.

#!/bin/bash
for file in ./*
do
  if [ ${file: -4} == ".txt" ]
  then
    cat $file >> concatFile.txt 
  fi
done

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

The Linux Command Line

Take your Linux skills to the next level! Try Linux & UNIX

The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.

$ Check price
39.9539.95Amazon 4.5 logo(274+ reviews)

More Linux & UNIX resources

Ad