Different form of loops in Bash

By xngo on February 21, 2019

Overview

Looping is needed when you want to process over a bunch of data. Use it sparingly as it is overtly expensive and slow. Often times, simple loop process can be replaced by a one-liner using a combination of the powerful commands such as find, sed, tr, xargs, etc. Different forms of loops are showcased below. My favorite is the While loop. It is the king of all loops. It can handle filename with spaces and allow incremental counter.

While loop

counter
while IFS='' read -r line || [[ -n "${line}" ]]; do
    echo "Do something ${line}"
    let counter+=1
done < <( cat somefile.txt | grep -v '^#' | mawk NF )
echo ${counter}

Loop through an array of elements

animalNames=( cat dog fish )
animalNames+=( bird )
for animal in "${animalNames[@]}"; do
    echo "********  ${animal}  ********"
done

Loop through arguments

for arg in "${@:2}"; do # Skip the first argument.
    echo "${arg}"
done

Loop from specific index and use a counter.

MAX=5
position=11
for ((i=0; i < MAX ; i++)); do
    echo "i=$i , position=$position"
    let position+=1 # Same as 'i=i+1
done
echo "Final position=${position}"

Loop through movie files

for movie in *.{mp4,mkv,avi,rmvb,webm}; do
    echo "${movie}" 
done

Loop through alphabet

for x in {a..z}
do
    echo "$x"
done

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.