Shell Scripting: Loops and Arrays

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Arrays

An array is a list of items, declared inside parentheses:

breeds=(husky setter "border collie" chiwawa)

Access items using square brackets (zero-indexed):

echo ${breeds[0]}  # husky
echo ${breeds[1]}  # setter

Get the total number of items:

echo ${#breeds[@]}  # 4

Looping Over Arrays

Use a for loop to iterate over array elements:

list=( "first" "second" "third" )

for i in "${list[@]}"
do
  echo $i
done

Output:

first
second
third

For Loop with Ranges

Loop through a range of numbers:

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

This is also useful for creating multiple folders:

mkdir {1..30}

This creates folders named 1, 2, 3… up to 30.

For Loop with C-style Syntax

for ((i=0; i<5; i++))
do
  echo $i
done

While Loop

Execute while a condition is true:

count=0
while [ $count -lt 5 ]
do
  echo $count
  ((count++))
done

Until Loop

Execute until a condition becomes true:

count=0
until [ $count -ge 5 ]
do
  echo $count
  ((count++))
done

Practical Example

Here’s a script that iterates over an array of book folders:

#!/bin/sh

books=( "c-handbook" "css-handbook" "js-handbook" )

for book in "${books[@]}"
do
  echo "Processing $book"
  cd $book
  # do something with the book
  cd ..
done

Select Menu

Create an interactive menu:

#!/bin/bash
select breed in husky setter "border collie" chiwawa STOP
do
  if [ "$breed" == "" ]; then
    echo "Please choose one"
  else
    break
  fi
done

echo "You chose $breed"

This displays a numbered menu and waits for user input.

Lessons in this unit:

0: Introduction
1: Introduction to Shells
2: Bash Basics
3: Writing Shell Scripts
4: Variables and Environment Variables
5: ▶︎ Loops and Arrays
6: Shell Script Functions
7: Creating Aliases
8: Tips and Tricks
9: The Fish Shell
10: Persist aliases and other configuration in Fish Shell
11: How to add a path to Fish Shell
12: Fish Shell, how to avoid recording commands to history
13: Fish Shell, how to remove the welcome message
14: How to replace all filenames with space with underscore using a shell script
15: How to update all npm packages in multiple projects that sit in subfolders