Search⌘ K
AI Features

Loops

Explore the fundamentals of Bash scripting by mastering for and while loops, as well as case statements for handling command-line options with getopts. This lesson helps you understand loop control and argument parsing, enabling you to write more effective and versatile shell scripts.

How Important is this Lesson?

For and while loops are a basic construct in most programming languages, and bash is no exception.

for Loops

First you’re going to run a for loop in a ‘traditional’ way:

Shell
for (( i=0; i < 20; i++ ))
do
echo $i
echo $i > file${i}.txt
done
ls
Terminal 1
Terminal
Loading...
  • You just created twenty files, each with a number in them using a for loop in the ‘C’ language style (line 1)

  • Note there’s no $ sign involved in the variable when it’s in the double parentheses!

  • Line 3 echoes the value of i in each iteration

  • line 4 redirects that value to a file called file{$i}.txt, where ${i} is replaced with its value in that iteration

  • Line 6 shows the listing of files created

Shell
for f in $(ls *txt)
do
echo "File $f contains: $(cat $f)"
done

It’s our old friend the command substitution! The command substitution lists all the files we have.

This for loop uses the in keyword to separate the variable each iteration will assign to f and the list to take items from. Here bash evaluates ...