Pages

Sunday, April 10, 2016

while condition one liners

Home

To print values till 10 using while
# COUNTER=0; while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done

To create an infinite loop using while that exits on CTRL+C key
# while true; do
echo -n "Make your choice: "
read value
echo
echo "You Entered $value "
done
To calculate factorial using while loop:
#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
   factorial=$(( $factorial * $counter ))
   counter=$(( $counter - 1 ))
done
echo $factorial
While loops are frequently used for reading data line by line from file:
#!/bin/bash
FILE=$1
# read $FILE using the file descriptors
exec 3<&0
exec 0<$FILE
while read line
do
      # use $line variable to process line
      echo $line
done
exec 0<&3
Conditional while loop with break statement
while [ condition ]
do
   statements1      #Executed as long as condition is true and/or, up to a disaster-condition if any.
   statements2
  if (disaster-condition)
  then
      break                #Abandon the while lopp.
  fi
  statements3          #While good and, no disaster-condition.

done

Back To Top
Home

No comments:

Post a Comment