Loops
In this lesson, you will cover for loops, case statements, and while loops in bash. This lesson will quickly take you through the various forms of looping that you might come across, including 'while' loops, 'case' statements, 'for' loops, and 'C-style' loops.
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:
for (( i=0; i < 20; i++ ))doecho $iecho $i > file${i}.txtdonels
-
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
echo
es the value ofi
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
for f in $(ls *txt)doecho "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 ...