Shell learning notes and shell scripts
1. for Loop 1. Syntax format 1
For variable in value 1 value 2 value 3... do program done
Note: The program will traverse all values, assign values to variables, and then execute the program. That is to say, the number of subsequent values will be the number of times the program loops.
2. Example 1: traverse 5 numbers for output
#! /Bin/bashfor I in 1 2 3 4 5do echo $ idone # output result 12345
3. Example 2: traverse all files in the directory and output the file name
#! /Bin/bashfor file in $ (ls) # Note: ls will list all the files in the current directory and assign values to the files one by one. Then do echo $ filedone can be output one by one.
4. Syntax Format 2
For (initial value; cyclic control condition; variable change) do program done
Note: This format is the same as that of the C for loop. The difference is that the loop conditions must be enclosed in double brackets.
5. Example 1: Calculate the sum of 1 to 100.
#! /Bin/bashsum = 0for (I = 1; I <= 100; I = I + 1) do sum = $ ($ sum + $ I )) # It can also be used, sum = $ [$ sum + $ I] doneecho $ sum # output 5050
Ii. while loop 1. Syntax format
While [conditional statement] do program done
Note: When the conditional statement is set to true, the program will be executed until the conditional statement fails to exit the loop.
2. Example: Calculate the sum from 1 to 100
#! /Bin/bashi = 1sum = 0 while [$ I-le 100] do sum = $ (sum + I) I = $ (I + 1 )) doneecho $ sum # output 5050
Iii. until loop 1. Syntax format
Until [conditional statement] do program done
Note: The until loop is the opposite of the while loop. When the conditional statement is invalid, the program will be executed until the conditional statement is set up to exit the loop.
2. Example: Calculate the sum from 1 to 100
#! /Bin/bashi = 1sum = 0 until [$ I-gt 100] do sum = $ (sum + I) I = $ (I + 1 )) doneecho $ sum # output result 5050