Similar to other programming languages, the shell supports A for loop.
The general format for A for loop is:
for inch List Do command1 command2 ... CommandN Done
A list is a sequence of values (numbers, strings, and so on), each separated by a space. Each time the loop is passed, the next value in the list is assigned to the variable.
The in list is optional, if it is not used, the For loop uses the command-line positional parameters.
For example, sequentially output the numbers in the current list:
#!/bin/bashfor in12345 do Echo " The value is: $loop " Done
Operation Result:
The value is:1Thevalue was:2Thevalueis:3Thevalueis:4 the value is:5
#!/bin/Bashnum=1 forStrinch 'This is a string' 'Test' Do Echo$num Num=$[$num +1] Echo$str DoneNum=1 forStrinch 'This is a string' Do Echo$num Num=$[$num +1] Echo$str Done
Operation Result:
1string2test1string
Show files starting with. Bash in the home directory:
#!/bin/bash $HOME/.bash* do echo $FILEDone for in doing echo $FILE Done
Operation Result:
/root/. bash_history/root/. Bash_logout/root/. Bash_profile/ROOT/.BASHRC
Normal for loop
#!/bin/bashecho 'expr44' for ((i=110 ; i++) does Echo $ (expr4)Done ~
Method 1:
For variable in constant list; do some commands; done;
for file in $ (ls); Do echo $file; Done
for inch 1 2 3 4 5; Do Echo done;
Method 2:
For (variable initialization; condition judgment; variable self); do some commands; done;
for ((i=0; i<doecho Done
#!/bin/bashmax =10 for (I=0 ; i < MAX; I++ do $i done for ((I=0 ; i < $MAX; i++< Span style= "color: #000000;" )) do echo $i done
#/bin/Bashmax=Ten for ((i=0; i < MAX; i++))do Echo $ (expr $i \* $i) echo $[$i * $i] Done
Shell for Loop