For Loop example
For Loop Syntax:
1for VARIABLE in 1 2 3 4 5 .. N2do3command14command25 commandN6 done
01
#! /Bin/bash0203foriin1 2 3 4 50405do0607 echo "Welcome $ I times"0809 done10
Bash version 3.0 +
#! /Bin/bash For I in {1 .. 5} Do Echo "Welcome $ I times" Done
Bash version 4
#! /Bin/bash Echo "Bash version $ {BASH_VERSION }..." For I in {0... 10... 2} Do Echo "Welcome $ I times" Done
Syntax example with "seq" command
#! /Bin/bash For I in $ (seq 1 2 20) Do Echo "Welcome $ I times" Done
Three expressions of the for Loop
Syntax:
For (EXP1; EXP2; EXP3 ))DoCommand1Command2Command3Done
Example:
#! /Bin/bashFor (c = 1; c <= 5; c ++ ))DoEcho "Welcome $ c times ..."Done
Effect:
Welcome 1 timesWelcome 2 timesWelcome 3 timesWelcome 4 timesWelcome 5 times
For infinite loop
#! /Bin/bash For ((;;)) Do Echo "infinite loops [hit CTRL + C to stop]" Done
Break Condition Statement
For I in 1 2 3 4 5DoStatements1 # Executed for all values of ''I ', up to a disaster-condition if any.Statements2If (disaster-condition)ThenBreak # Abandon the loop.FiStatements3 # 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/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
Continue Condition Statement
For I in 1 2 3 4 5DoStatements1 # Executed for all values of ''I ', up to a disaster-condition if any.Statements2If (condition)ThenContinue # Go to next iteration of I in the loop and skip statements3FiStatements3Done
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/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 cp command Fi # We are hear means no backup file exists, just use cp command to copy file /Bin/cp $ f. bak Done