FOR loops & WHILE statements

Introduction to Bash Scripting

Alex Scriven

Data Scientist

Basic FOR Loop structure

Python:

for x in range(3):
    print(x)
0
1
2

R:

for (x in seq(3)){
    print(x)
}
[1] 1
[1] 2
[1] 3
Introduction to Bash Scripting

FOR Loop in Bash

The basic structure in Bash is a similar:

for x in 1 2 3

do echo $x done
1
2
3
Introduction to Bash Scripting

FOR loop number ranges

Bash has a neat way to create a numeric range called 'brace expansion':

  • {START..STOP..INCREMENT}
for x in {1..5..2}

do echo $x done
1
3
5
Introduction to Bash Scripting

FOR loop three expression syntax

Another common way to write FOR loops is the 'three expression' syntax.

  • Surround three expressions with double parentheses
  • The first part is the start expression (x=2)
  • The middle part is the terminating condition (x<=4)
  • The end part is the increment (or decrement) expression (x+=2)

 

 

for ((x=2;x<=4;x+=2))
do 
    echo $x
done
2
4
Introduction to Bash Scripting

Glob expansions

Bash also allows pattern-matching expansions into a for loop using the * symbol such as files in a directory.

For example, assume there are two text documents in the folder /books:

for book in books/*
do  
    echo $book
done
books/book1.txt
books/book2.txt
Introduction to Bash Scripting

Shell-within-a-shell revisited

Remember creating a shell-within-a-shell using $() notation?

You can call in-place for a for loop!

Let's assume a folder structure like so:

Structure of books directory

Introduction to Bash Scripting

Shell-within-a-shell to FOR loop

We could loop through the result of a call to shell-within-a-shell:

for book in $(ls books/ | grep -i 'air')

do echo $book done
AirportBook.txt
FairMarketBook.txt
Introduction to Bash Scripting

WHILE statement syntax

Similar to a FOR loop. Except you set a condition which is tested at each iteration.

Iterations continue until this is no longer met!

  • Use the word while instead of for
  • Surround the condition in square brackets
    • Use of same flags for numerical comparison from IF statements (such as -le)
  • Multiple conditions can be chained or use double-brackets just like 'IF' statements along with && (AND) or || (OR)
  • Ensure there is a change inside the code that will trigger a stop (else you may have an infinite loop!)
Introduction to Bash Scripting

WHILE statement example

Here is a simple example:

x=1

while [ $x -le 3 ];
do echo $x ((x+=1)) done
1
2
3
Introduction to Bash Scripting

Beware the infinite loop

Beware the infinite WHILE loop, if the break condition is never met.

x=1
while [ $x -le 3 ]; 
do
    echo $x
    # don't increment x. It never reaches 3!
    # ((x+=1)) 
done

This will print out 1 forever!

Introduction to Bash Scripting

Let's practice!

Introduction to Bash Scripting

Preparing Video For Download...