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:
- Pick up the apple โ do something with it.
- Pick up the banana โ do something with it.
- 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 for ... in ... 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.
Top comments (0)