forcycle

The basic format of the for loop in bash shell:

for var in list 
do
commands
done
Copy the code

It is also possible to put the do statement and the for statement on the same line, but they must be separated from the values in the list by a semicolon :for var in list; do

Example:

#! /bin/bash
# control flow
for item in I don\Don't know New York do echo echo: $item done #-------- execute script ------ #t
# output: know
# output: New
Output: York
Copy the code

Note:

  1. $itemThe value of the variable will remain the value of the last iteration and will remain inshellThe rest of the script remains valid until we modify it.
  2. The values in the list contain special symbols such as:'.:.;, and space. Otherwise, an exception will be executed. There are two ways to handle it:

First, use escape character \ escape special characters; Second, use double quotes to define values in a list that use special characters.

  1. forBy default, the loop assumes that every value in the list is separated by Spaces.

I don\’t know New York is a value containing more than one word in the list, so it should be escaped or quoted in order to display properly:

#! /bin/bash
# control flow
for item in I "don't" know "New York"
# oR: for item in I don't know New\ York
do
echoOutput:$item
done
#-------- Execute the script ------Output: I Output: donOutput: know output: New YorkCopy the code

Field separator

Bash shell has a special environment variable, IFS, called internal field separator.

What IFS does: If the Bash shell sees any of these characters in the data, it assumes that this indicates the start of a new data field in the list.

The default values of IFS are Spaces, tabs, and newlines.

With this understanding in mind, we assume that the data in test_file is as follows:

Bei Jing
is
beautiful city
Copy the code

Write a script for loop that reads the contents of test_file:

#! /bin/bash
# Field separator test
# command replace two ways: 1. 2. The $();
for item in `cat test_file`
do 
echoOutput:$item
done
Copy the code

The final result of the execution, based on the default IFS delimiter, appears as follows:

Output: Bei Output: Jing Output: is output: beautiful output: cityCopy the code

The answer is: modify the IFS environment variable to only newlines;

#! /bin/bash
# Field separator test
# command replace two ways: 1. 2. The $();

IFS=$'\n'
for item in `cat test_file`
do 
echoOutput:$item
done
#-------- Execute the script ------
# output: Jing
# output: is
Output: beautiful City
Copy the code

Alter test_file contents:

Bei:Jing is beautiful; cityCopy the code

IFS needs to specify multiple delimiters when each word is expected to be a data field. The script is as follows:

#! /bin/bash
# Field separator test
# command replace two ways: 1. 2. The $();

IFS=$'\n':'; '
for item in `cat test_file`
do 
echoOutput:$item
done
Copy the code

The results showed

Output: Bei Output: Jing Output: is output: beautiful output: cityCopy the code

Traverses the file directory

You can use the for command to automatically traverse files in a directory. When doing this, you must use the wildcard character :* in the filename or pathname.

#! /bin/bash
Pass through the file directory
filePath=~/desktop/compare/*
for file in $filePath
do
if [ -f "$file" ];then 
  echo $fileIs the fileelif [ -d "$file" ]
then
  echo $fileIs a directoryelse
   echootherfi
done
Copy the code

Note: it is possible to include Spaces in directories or file names. In the test command, the bash shell takes extra words as arguments, causing an error.

CLinguistically stylisticforcycle

The basic format is as follows:

for (( variable assignment ; condition ; iteration process ))
do
commands
done
Copy the code

Here’s a simple analogy:

for((a = 0; a < 10; a ++))
Copy the code

Note:

  1. Variable assignments can have Spaces;
  2. Variables in conditions do not start with a dollar character;
  3. Expr command format is not used in the calculation of iterative process.

Example:

#! /bin/bash
# 'C' style 'for' loop
for(( i = 0; i<10; i++))do
  echodigital$i
done
Copy the code

Multivariable examples:

#! /bin/bash
# 'C' style 'for' loop
for(( i = 0,j=10; i<10,j>7; i++,j--))do
  echoThe difference between j and I$j-$i
done

#----------- Execute the output -----------
The difference between j and I is 10 minus 0
The difference between j and I is 9 minus 1
The difference between j and I is 8 minus 2
Copy the code

whilecycle

The basic format of the while loop is as follows:

while test command 
do
other commands
done 
Copy the code

The test command returns a non-zero while loop to stop. Example:

#! /bin/bash
# ` while ` cycle
x=10
while [ $x -gt 7 ]
do
echoThe output$x
#bash is compatible with sh, so the basic format for integer arithmetic operations is' $[] '
x=$[$x1]done  
#----- Result -----
Output 10 #
Output # 9
# 8 output
Copy the code

untilcycle

The until loop is the opposite of the while loop, with the following basic format:

until test command
do
other commands
done
Copy the code

The basic semantics are: Execute other commands until command is established. The loop ends when the test command returns zero or succeeds. Example:

#! /bin/bash
# ` until ` cycle
x=10
until [ $x -le 7 ] # until x is less than or equal to 7
do
echoThe output$x
x=$[$x1]done
#---------- Execute script output ------------
Output 10 #
Output # 9
# 8 output
Copy the code

A nested loop

#! /bin/bash
Nested for loops
for (( a = 1; a <= 2; a++ ))
 do
   echo The external circulation can be divided into two groups.$a:"
   for (( b = 1; b <= 2; b++ ))
    do
      echo "Internal loop:$b"
    done
done
#----------- Execute the output ---------------External loop 1: internal loop: 1 Internal loop: 2 External loop 2: internal loop: 1 Internal loop: 2Copy the code

Control loop

The control loop uses break and continue. The use of these two keywords is similar to that of other languages.

  • Break: Can exit any type of loop.

1. When multiple loops are processed, the break command automatically terminates the innermost loop on which it is located.

The following is an example:

#! /bin/bash
Nested for loops
for (( a = 1; a <= 2; a++ ))
 do
   echo The external circulation can be divided into two groups.$a:"
   for (( b = 1; b <= 2; b++ ))
    do
      if [ $b -eq 2 ];then
      break
      fi
      echo "Internal loop:$b"
    done
done
#--------- Execute the output ----------External loop 1: internal loop: 1 External loop 2: internal loop: 1Copy the code

2. In the inner loop, to terminate the outer loop, break n can be used, where N indicates the level of the loop to break out. By default, n is 1. If n is set to 2, the break command terminates the next outer loop.

The following is an example:

#! /bin/bash
Nested for loops
for (( a = 1; a <= 2; a++ ))
 do
   echo The external circulation can be divided into two groups.$a:"
   for (( b = 1; b <= 2; b++ ))
    do
      if [ $b -eq 2 ];then
      break 2
      fi
      echo "Internal loop:$b"
    done
done
#------------ Execute the output -------------External loop 1: Internal loop 1Copy the code
  • Continue: You can terminate a loop early, but not completely.

Redirects the output of a loop to a file or command

The output of the redirect loop is shown as follows:

#! /bin/bash
Redirect the output of the loop
for (( a = 1; a <= 2; a++ ))
do
   echo The results show that the output of the loop is higher than that of the loop.$a"
done > test.txt

#-------test. TXT file contents -------Loop output 1 Loop output 2Copy the code

Enter the file contents into the loop as shown in the following example:

# File contentsHello; Hello world, world hi: iosCopy the code

Script and execute the output

#! /bin/bash
Redirect input to loop
while IFS="And:;" read -r x y 
do
    echo $x - $y
done < test.txt

#------- Execute the output -------
# Hello - world
#hello - world
#hi - ios
Copy the code

References:

Linux command line and shell scripting