Bash Loops

Examples of various looping scripts using bash

Arrays and Counts

Loop through an array

declare -a myArray=("Diane" 
"Jim" "Larry"
"Dawn"
)
for i in "${myArray[@]}"
do
echo $i
done

Loop through an incremental count

for INDEX in {0..5}; do
echo $INDEX
done

# one liner
for I in {0..5}; do echo $INDEX; done

 

For Loops

Use these with variables!

# Loops 5 times
START=0
END=4
for ((INDEX=$START; INDEX<=$END; INDEX++)) do
echo $INDEX
done

 

Files

Looping through items in a file

Using cat

for ITEM in `cat FILE.NAME`; 
do
   echo $ITEM
done

#one liner
for ITEM in `cat FILE.NAME`; do echo $ITEM; done

Redirecting the contents

while read ITEM; do
echo $ITEM
done < FILE.NAME

 

Sidebar