Loops

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
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $( ls -r )
do
  echo "$f"
done
IFS=$SAVEIFS