Pages

Sunday, April 10, 2016

for condition one liners

Home

To use basic for loop
for VARIABLE in 1 2 3 4 5 .. N
do
      command1
      command2
      commandN
done
OR
for VARIABLE in file1 file2 file3
do
      command1 on $VARIABLE
      command2
      commandN
done
OR
for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
      command1 on $OUTPUT
      command2 on $OUTPUT
      commandN
done
To work with numeric values in for loop
for i in 1 2 3 4 5
do
   echo "Current number is $i "
done
OR
for i in {1..5}
do
   echo "Welcome $i times"
done
OR
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do
     echo "Welcome $i times"
 done
Note:-syntax used in for loop is {START..END..INCREMENT}
To write traditional three condition for loop
for (( EXP1; EXP2; EXP3 ))
do
      command1
      command2
      command3
done
To create an infinite loop using for that exits on CTRL+C key
# for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done
Conditional for loop with 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

Back To Top
Home

No comments:

Post a Comment