Shell Scripting ProgramIterations - Part -2

Bash shell supports following

while loop in Shell scripting

Here is a sample where you can find the while loop which execute the commands until it reaches condition false for factorial number the iterate start with i that is initial value. Loop decrements i value and reaches to 0 then it exits.

#!/bin/bash
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 Number" >&2
  exit 1
fi
i=$1
f=1
echo "Given number is: " $1
while [ $i -gt 0 ]
do
   f=$(( $f * $i ))
   i=$(( $i - 1 ))
   echo "iterating $i"
done

echo "Factorial of "$1 " is " $f
Execution outcome is for you...


The for loop in Shell script


#!/bin/bash
# Description	: This script illustrate how to use for loop

for i in `ls`
 do
   if [ -f $i ];
   then
      echo $i is file
   elif [ -d $i ];
   then
      echo $i is directory
   fi
done

Execution of this for example...


Comments