1. for command
1.1 Use of for commands
bash shell provides
for
Command, create a loop that traverses a series of values. Each cycle uses one of the values to execute a defined set of commands. Below is the bash shellfor
Basic format of the command.
for var in list do commands done It can also be in this form for var in list; do
Pay attention to the
list
This is not the keyword of shell. List just wants to indicate that this is a list composed of values, characters, and strings. The for loop is used to iterate through this list.
use:
for i in a b c d e f do echo "The char is: $i" done ------------------------------ The char is: a The char is: b The char is: c The char is: d The char is: e The char is: f
for name in Alabama Alaska Arizona Arkansas California Colorado do echo The next state is $name done --------------------------------------------------------------- The next state is Alabama The next state is Alaska The next state is Arizona The next state is Arkansas The next state is California The next state is Colorado
You can also load values in variables:
Usually a shell script encounters a situation where you store a series of values in one variable, and then you need to iterate through the entire list in the variable.
str="hello, word" for s in str do echo "$s" done
You can also load values in the command:
Another way to generate the required values in the list is to use the output of the command. You can use a command to execute any command that produces an output, and then use the output of that command in the for command.
file="file_name" for f in $(cat $file) do echo "$f" done
1.2 Problems facing for commands
For loops can traverse a list of strings, for example
Alabama Alaska Arizona Arkansas California Colorado
, this is very simple, but if the string is mixed with special characters, such asthis'll
Then this is a bit troublesome, because some special characters have other meanings in the shell. To solve this problem, a backslash needs to be added to the string\
Escape, like thisthis\'ll
. At this time the shell can recognize special characters.
Another way is to enclose strings containing special characters in double quotes, such as"this'll"
。
For example:
for s in I don\'t know if "this'll" work do echo "word:$s" done
1.3 Change the field separator
Why do you need to change the field separator? If you need to output an English article, the content of the English article will naturally exist between words.Spaces, between linesLine breaksNow if the field separator of the shell output content isSpaces, then there is a problem with this, that is, when the content is output, the content will be arranged in a row, rather than the output line by line. The reason for this problem is the special environment variable IFS, called the internal field separator. IFS environment variables define a series of characters used by bash shell as field separator. By default, the bash shell treats the following characters as field separators:
- Spaces
- Tab symbols
- Line breaks
If the bash shell sees any of these characters in the data, it assumes that this indicates the beginning of a new data field in the list.
To solve this problem, you can temporarily change the value of the IFS environment variable in the shell script to limit characters that are treated as field separators by the bash shell, for example
IFS=$'\n'
, so that the field separator is changed toLine breakNow. In this way, the bash shell thinksLine breakThis is the end of the data, and the bash shell ignores spaces and tabs in the data value.
Store old values like the following, assign temporary modification values:
file="file_name" =$IFS IFS=$'\n' for f in $(cat $file) do echo "$f" done IFS=$
1.4 Reading directories with wildcards
You can use the for command to automatically traverse files in the directory. When doing this, you must use wildcards in the file name or path name. It forces the shell to use file extension to match. File extension matching is the process of generating a file name or path name that matches the specified wildcard character. This feature is very useful when dealing with files in directories without knowing all file names.
Load all files and folders from the directory:
for file in /home/rich/test/* do if [ -d "$file" ] then echo "$file is a directory" elif [ -f "$file" ] then echo "$file is a file" fi done
2. c style for command
Let’s first take a look at the code style of for loops in C language code:
for (i = 0; i < 10; i++) { printf("The next number is %d\n", i); }
The following is the basic format of the C-style for loop in bash shell:
for (( variable assignment ; condition ; iteration process )) ↓↓↓ for (( a = 1; a < 10; a++ ))
The C-style for loop format will make bash shell script programmers confused because it uses C-style
variable references instead of shell-style variable references.
Note that some parts do not follow the bash shell standard for command:Variable assignments can have spaces
Variables in the condition do not start with the dollar sign
The formula of the iteration process is not used expr command format
Using the C-style for command, you can use multiple variables like C, for example:
for (( a=1, b=10; a <= 10; a++, b-- )) do echo "$a - $b" done
3. while command
The key to the while command is that the exit status code of the specified test command must change with the command running in the loop. If the exit status code does not change, the while loop will continue. The most common usage of test command is to use square brackets to check the value of shell variables used in loop commands.
while test command do other commands done
Example:
while [ $a -gt 0 ] do echo $a a=$[ $a - 1 ] done
While you can also use multiple test commands
The while command allows you to define multiple test commands on the while statement line. onlyThe last oneThe exit status code of the test command is used to determine when the loop is ended.
while echo $a [ $a -ge 0 ] do echo "This is inside the loop" a=$[ $a - 1 ] done
4. until command
until
Commands andwhile
Commands work in the exact opposite way.until
The command requires you to specify a test command that usually returns a non-zero exit status code.Only when the exit status code of the test command is not 0, the bash shell will execute the commands listed in the loop.. Once the test command returns the exit status code 0, the loop ends.
until test command do other commands done
Example:
until [ $a -eq 0 ] do echo $a a=$[ $a - 25 ] done
5. Control loop
Sometimes when we execute loops in scripts, we need to exit the loop in time according to specific conditions to execute other tasks, so we must be able to control the loop conditionally. In the shell
break
Order,continue
Commands can help us control the situation inside the loop.
5.1. break command
The break command is an easy way to exit the loop. You can use the break command to exit any type of loop, including while and until loops.
When the shell executes the break command, it tries to jump out of the currently executing loop.
Sometimes you are looping internally, but you need to stop the external loop.break
The command accepts a single command line parameter value.break n
where n specifies the loop level to jump out. By default, n is 1 , indicating that the current loop is jumped out. If you set n to 2 , the break command stops the outer loop at the next level.
5.2. Continue Command
continue
Commands can abort commands in a loop in advance, but do not completely terminate the entire loop. For example, terminate this loop early and enter the next loop (when the shell executes the continue command, it skips the remaining commands in the while loop).
This is the end of this article about the detailed explanation of shell loop commands. For more related shell loop command content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!