Bash Loops

Bash Loops

Learn about for and while loops in Bash

Loops are important in any Turing complete programming language because they allow programs to repeat blocks of code. This repetition allows programs to:

  • Process large amounts of data without writing repetitive code

  • Iterate over collections of data like arrays and lists

  • Implement algorithms that require repeating steps

Without loops, programs would not be able to scale efficiently and would have to manually write out repetitive code for each iteration.

Some examples of Bash scripts that use loops:

  • Reading input from a file and processing each line using a while read loop
while IFS= read -r line; do
   # process $line 
done < "input.txt"
  • Iterating over a range of numbers using for loop:
for i in {1..10}; do 
   echo "Number is $i"
done
  • Processing command line arguments using for loop:
for arg in "$@"
do
    echo "Argument is $arg"
done
  • Running a command multiple times using while loop:
count=1
while [ $count -le 5 ] 
do
    command
    count=$((count+1))
done

In Bash, we have for, while and until loops. They allow us to:

  • Repeat a block of code a fixed number of times (for)

  • Repeat while/until a condition is met (while, until)

Loops are an essential construct in Bash and any programming language as they allow programs to scale and perform repetitive tasks efficiently.


REPL Applications

A CLI REPL (Read-Eval-Print Loop) application is an interactive command line interface that:

  • Reads input from the user

  • Evaluates the input

  • Prints the output

  • Loops, allowing the user to enter more input

It's a simple but powerful type of program that acts as an interactive shell for evaluating expressions, running commands, or interacting with an API.

An example of a REPL application could be:

Enter command (h for help): 
> hello
Hello!

Enter command (h for help):
> h
Options:
add - Adds two numbers    
subtract - Subtracts two numbers
exit - Exits the program

Enter command (h for help):
> add 
Enter two numbers:
> 1 2
Result: 3

Enter command (h for help):
> subtract  
Enter two numbers:
> 5 3  
Result: 2

Enter command (h for help):
> exit
Goodbye!

We can implement this using a loop like:

options = ['add', 'subtract', 'exit']

while True:
    command = input("Enter command (h for help): ")

    if command == 'h':
        # Print help

    elif command in options:
        if command == 'add':
            # Get input and calculate sum

        elif command == 'subtract':
            # Get input and calculate difference  

    elif command == 'exit':
        break

    else:
        print("Invalid command")

The loop continously prompts the user for input, evaluates the command, prints output, and loops again - forming a REPL. We use options to define the set of available commands and handle invalid input.


Disclaim: This article was created with AI (rix). If you want to learn more, I have a full Bash programming course prepared where I use diagrams to explain Bash in a logic way. Join Sage-Code Laboratory to get access for my course.

sagecode.net