For Loop example
For Loop Syntax:
for VARIABLE in 1 2 3 4 5 .. Ndo command1 command2 commandNdone
#!/bin/bashfor i in 1 2 3 4 5doecho "Welcome $i times"done
Bash version 3.0 +Version
#!/bin/bash for i in {1..5}do echo "Welcome $i times"done
Bash version 4Version
#!/bin/bashecho "Bash version ${BASH_VERSION}..."for i in {0..10..2} do echo "Welcome $i times" done
Syntax example with "seq" command
#!/bin/bashfor i in $(seq 1 2 20)do echo "Welcome $i times"done
Three expressions of the for Loop
Syntax:
for (( EXP1; EXP2; EXP3 ))do command1 command2 command3done
Example:
#!/bin/bashfor (( c=1; c<=5; c++ ))do echo "Welcome $c times..."done
Effect:
Welcome 1 timesWelcome 2 timesWelcome 3 timesWelcome 4 timesWelcome 5 times
For infinite loop
#!/bin/bashfor (( ; ; ))do echo "infinite loops [ hit CTRL+C to stop]"done
Break Condition Statement
for I in 1 2 3 4 5do 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
The following shell script stores all the files in the/etc directory. The for loop will discard the file found in/etc/resolv. conf.
#!/bin/bashfor 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 fidone
Continue Condition Statement
for I in 1 2 3 4 5do 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 statements3done
Use this script to back up all file names specified in the command line. If. The bak file exists. It skips the cp command.
#!/bin/bashFILES="$@"for f in $FILESdo # if .bak backup file exists, read next file if [ -f ${f}.bak ] then echo "Skiping $f file..." continue # read next file and skip cp command fi # we are hear means no backup file exists, just use cp command to copy file /bin/cp $f $f.bakdone