DEV Community

Cover image for Learn Bash Scripting With Me ๐Ÿš€ - Day 5
Babs
Babs

Posted on

Learn Bash Scripting With Me ๐Ÿš€ - Day 5

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode
  • The above starts a for loop with FRUITS being the variable name.
$(cat fruits.txt);
Enter fullscreen mode Exit fullscreen mode
  • 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"
Enter fullscreen mode Exit fullscreen mode
  • 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)