Learn Bash Scripting With Me πŸš€ – Day 5



This content originally appeared on DEV Community and was authored by Babs

Day 5 – for loop

In case you’d like to revisit or catch up on what we covered on Day Four, here’s the link:

https://dev.to/babsarena/learn-bash-scripting-with-me-day-4-fo7

In Bash, a for loop is used to iterate over a list of items (strings, numbers, files, command outputs, etc.) and execute a block of code repeatedly for each item.

It helps automate repetitive tasks without having to write the same command multiple times.

Iterate simply means to repeat a process step by step.

Imagine you have a basket of fruits:
apple, banana, cherry

If you iterate over the basket, you:

  1. Pick up the apple β†’ do something with it.
  2. Pick up the banana β†’ do something with it.
  3. Pick up the cherry β†’ do something with it.

Creating A For Loop Script

  • First, we’ll create a file that contains a list of fruits. Later, we’ll use this file in a for loop.

The image above shows a text file I created, named fruits.txt, which contains a list of five fruits.

The Script

The image above is a simple for loop script created, so I will be explaining the script below.

Explanation

#!/bin/bash
  • The above is called a shebang, It tells the system to use the Bash shell to run this script.
for FRUITS in $(cat fruits.txt);
  • The above starts a for loop with FRUITS being the variable name.
$(cat fruits.txt);
  • The above runs the cat command, which reads the contents of the file fruits.txt.

Purpose of the semicolon

  • In Bash, the semicolon (;) is used to separate two commands written on the same line.

  • The semicolon here tells Bash:

  • 👉 “The forin … command part is finished, and the next command (do) begins.”

NB- If you write do on a new line, you don’t need the semicolon but I am used to it that’s why I included it.

  • do … done

  • Everything between do and done will run once for each fruit in the list.

echo "I enjoy eating $FRUITS"
  • echo prints text to the terminal.

  • $FRUITS is replaced with the fruits from the list.

The image above is the output of the script we ran.

✅ In Summary: This script reads a list of fruits from a file (fruits.txt) and prints a custom message for each fruit using a for loop.


This content originally appeared on DEV Community and was authored by Babs