Linux bash for loop

Q. How do I use bash for loop under Linux operating systems?

A. for loop is used to process group of files or for other automation purposes.

Linux bash for loop syntax

for variable in list
do
   echo $variable
done

for variable in list
do
echo $variable
done

To loop through all files in a directory, enter:

for file in *
do
   echo $file
done

for file in *
do
echo $file
done

To print number 1 to 10, enter:

for n in {1..10}
do
   echo $n
done

for n in {1..10}
do
echo $n
done

Shell script to print odd and even number using a for loop

#!/bin/bash
for n in {1..10}
do
   out=$(( $n % 2 ))
   if [ $out -eq 0 ] 
   then
	echo "$n is even number"
   else
	echo "$n is ODD number"	
   fi	
done

#!/bin/bash
for n in {1..10}
do
out=$(( $n % 2 ))
if [ $out -eq 0 ]
then
echo "$n is even number"
else
echo "$n is ODD number"
fi
done

See more bash for loop examples here.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.