Chapter 2: more structured commands
For
Basic Format
for var in listdo commandsdone
You can specify the list in the following ways:
1. List
for var in A B C D
If the listed strings contain special characters, such as single quotes
1) Use escape characters
2) double quotation marks
2. Read the list from the variable
list="A B C D"list=$list" E"for var in $list
3. Read the value from the command
for var in `cat $file`
Note: In this case, line feed is also a field separator.
After the for loop ends, $ var saves the last value in the list.
Change field separator
Environment variable IFS: internal field separator, internal field separator
By default, spaces, tabs, and line breaks are field delimiters.
Modify:
IFS=$'\n'IFS=:IFS=$'\n:;"'
(What is the above $)
If you only want to temporarily modify
IFS. Old = $ IFS
Ifs = $ '\ N'
Ifs = $ ifs. Old
Use wildcards to read Directories
You can use the for command to traverse the directory, but you must use wildcards in the file name or path name. It forces shell to use file extension matching (file globbing)
File Extension matching is the process of generating a file name or path that matches the specified wildcard.
For file in/home/su1216/test/*/home/su1216/abcdo if [-d "$ file"] # If the file name contains spaces, enclose it with quotation marks then Echo "$ file is a directory" Elif [-F "$ file"] echo "$ file is a file" else echo "$ file is not exist "fidone
C-language for commands
For (a = 1; A <10; A ++ ))
Note:
1) assign values to variables with spaces
2) The variable in the condition does not start with the dollar sign
3) the formula in the iteration process does not use the expr Command Format
Use multiple variables
for (( a = 1, b = 10; a <= 10; a++ ,b-- ))do echo "$a - $b"done
While command
while test commanddo other commandsdone
Determine whether to continue the Loop Based on the exit status code of the test command.
Use multiple test commands
Only the exit status code of the last test command is used to determine when to exit the loop.
var1=10while echo $var1 [ $var1 -ge 0 ]do echo "This is inside the loop" var1=$[ $var1 - 1 ]done
Note: Each test condition is on a separate row. During each iteration, all test conditions are executed!
Until command
Unlike while
Basic Format
until test commandsdo other commandsdone
You can also have multiple test commands
Nested loop
var1=3until [ $var1 -eq 0 ]do echo "Outer loop: $var1" var2=1 while [ $var2 -lt 5 ] do var3='echo "scale=4; $var1 / $var2 | bc"' echo " Inner loop:$var1 / $var2 = $var3" var2=$[ $var2 + 1 ] done var1=$[ $var1 - 1 ]done
Control Loop
Break
Continue
Both of them can specify the number of hop-out/continue cycles.
Break n
Continue n
N is 1 by default.
Processing loop output
You can take over the output after the loop done, for example
for var in A B Cdo echo "$var"done > out.txt
You can also use pipelines.
for var in A B Cdo echo "$var"done | sort
Repost the following link
My blog address
Http://su1216.iteye.com/
Http://blog.csdn.net/su1216/