onlyforbopi
9/26/2018 - 12:46 PM

BASH LOOPS

  1. While with multiple conditions
  2. For loops
# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]

# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]

# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]

# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]

# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))

# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))



#####################################
#####################################

WHILE LOOPS

Structure : 

while [ condition ]
do
   command1
   command2
   command3
done


-----

While - Simple Increment

#!/bin/bash
x=1
while [ $x -le 5 ]
do
  echo "Welcome $x times"
  x=$(( $x + 1 ))
done

#!/bin/bash
counter=$1
factorial=1
while [ $counter -gt 0 ]
do
   factorial=$(( $factorial * $counter ))
   counter=$(( $counter - 1 ))
done
echo $factorial

----

While - read file line by line

#!/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

-----

While - Parse arguments

while getopts ae:f:hd:s:qx: option
do
        case "${option}"
        in
                a) ALARM="TRUE";;
                e) ADMIN=${OPTARG};;
                d) DOMAIN=${OPTARG};;
                f) SERVERFILE=$OPTARG;;
                s) WHOIS_SERVER=$OPTARG;;
                q) QUIET="TRUE";;
                x) WARNDAYS=$OPTARG;;
                \?) usage
                    exit 1;;
        esac
done
.......
..


-----

While - Infinite Loops

#!/bin/bash
while :
do
	echo "infinite loops [ hit CTRL+C to stop]"
done


-----

While + Break 

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

#!/bin/bash
 
while :
do
	read -p "Enter two numnbers ( - 1 to quit ) : " a b
	if [ $a -eq -1 ]
	then
		break
	fi
	ans=$(( a + b ))
	echo $ans
done

-----

While + Continue

while [ condition ]
do
  statements1      #Executed as long as condition is true and/or, up to a disaster-condition if any.
  statements2
  if (condition)
  then
	continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done
########################################################
########################################################

LOOPS (FOR / WHILE / UNTIL)

a. for VARIABLE in 1 2 3 4 5 .. N
	do
	command1
	command2
	commandN
	done
	
	EX : for i in 1 2 3 4 5
			do
			echo "Welcome $i times"
			done
			
	EX2 : for i in {1..5}
			do
			echo "Welcome $i times"
			done		

------			
			
B.  #!/bin/bash
        for i in $( ls ); do
            echo item: $i
        done
		
-------		
		
C. #!/bin/bash
        for i in `seq 1 10`;
        do
                echo $i
        done    
	
	Bash v4.0+ has inbuilt support for setting up a step value using {START..END..INCREMENT} syntax:

	#!/bin/bash
	echo "Bash version ${BASH_VERSION}..."
	for i in {0..10..2}
	do
     echo "Welcome $i times"
	done
		
-------
D. for VARIABLE in file1 file2 file3
	do
	command1 on $VARIABLE
	command2
	commandN
	done

------	
	
E.	for OUTPUT in $(Linux-Or-Unix-Command-Here)
	do
	command1 on $OUTPUT
	command2 on $OUTPUT
	commandN
	done

------
	
F.

Three-expression bash for loops syntax

This type of for loop share a common heritage with the C programming language. It is characterized by a three-parameter loop control expression; consisting of an initializer (EXP1), a loop-test or condition (EXP2), and a counting expression (EXP3).

for (( EXP1; EXP2; EXP3 ))
do
	command1
	command2
	command3
done
A representative three-expression example in bash as follows:

#!/bin/bash
for (( c=1; c<=5; c++ ))
do
   echo "Welcome $c times"
done

------

G. INFINITE FOR LOOP

#!/bin/bash
for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done

-----

H. FOR WITH CONDITIONAL + BREAK

for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (disaster-condition)
  then
	break       	   #Abandon the loop.
  fi
  statements3          #While good and, no disaster-condition.
done


EX : #!/bin/bash
for file in /etc/*
do
	if [ "${file}" == "/etc/resolv.conf" ]
	then
		countNameservers=$(grep -c nameserver /etc/resolv.conf)
		echo "Total  ${countNameservers} nameservers defined in ${file}"
		break
	fi
done

-------

J. FOR LOOP WITH CONTINUE

for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (condition)
  then
	continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done

ex : 
#!/bin/bash
FILES="$@"
for f in $FILES
do
        # if .bak backup file exists, read next file
	if [ -f ${f}.bak ]
	then
		echo "Skiping $f file..."
		continue  # read next file and skip the cp command
	fi
        # we are here means no backup file exists, just use cp command to copy file
	/bin/cp $f $f.bak
done

--------

K. for FILE in DIRECTORY
   do
     command1
	 command2
	 command3
   done