Bash - Loops

By xngo on June 17, 2019

Looping in Bash programming language refers to a statement where it allows your code to execute repeatedly. Bash provides different style of loops. Here are the examples.

For loop

#!/bin/bash
# Display each filename returned by ls.
for i in $( ls -r ); do
    echo "$i"
done
# -------------------- OR --------------------
# You can also move 'do' down
for i in $( ls -r )
do
    echo "$i"
done

C-style for loop

#!/bin/bash
# Display from 0 to 20.
MAX=20
for ((i=0; i <= MAX ; i++))  # Double parentheses, and "MAX" with no "$".
do
    echo $i
done

While loop

#!/bin/bash 
# Display 0 to 10.
i=0
while [  $i -lt 10 ]; do
    echo $i
    let i+=1 # Same as 'i=i+1'
done

Until loop

#!/bin/bash 
# Display 10 to 0.
i=10
until [  $i -lt 0 ]; do
    echo $i
    let i=i-1 # Same as 'i-=1'
done

For loop with file names with spaces

#!/bin/bash
 
# Changing internal field separator($IFS) to accept spaces
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $( ls -r )
do
  echo "$f"
done
 
# Restore $IFS
IFS=$SAVEIFS

Loop through array list

#!/bin/bash
 
# List of animal names
animalNames=( cat dog fish )
animalNames+=( bird )
for animal in "${animalNames[@]}"
do
  echo "********  ${animal}  ********"
done

Save data in array

LS_ARRAY=()
while IFS='' read -r LINE || [[ -n "$LINE" ]]; do
 
  LS_ARRAY+=("${LINE}")
  ((linecount++))
 
done < <( ls * )
echo "total number of lines: $linecount"
 
# http://mywiki.wooledge.org/BashFAQ/024

Use indirection to access argument values

for (( i=1; i<=$#; i++)); do
    echo "${!i}"
done
# http://unix.stackexchange.com/a/261186

Loop through each argument

for file in "$@"
do
  rm -f "${file}" && 
  touch "${file}"
 
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.