A script used shell to extract data from the database to generate a. xml file. Only 1000 pieces of data are generated in each file. So the while read line is used as the loop.
A problem was found during file counter creation. During execution, the file counter (filenum) always returns the initial value. The specific simplified script is as follows:
#/Bin/bash
Filenum = 1
For I in (multiple tables)
Do
# SQL statement>. Swap
Counter = 0
Cat. Swap | whileRead lineDo
# Variable assignment and file writing (not important, not detailed)
Counter = $ [counter + 1]
If [$ counter-EQ 1000]
Then
# Encapsulation operation. $ filename is included in the package name)
Filenum = $ [filenum + 1]
FiDone
# For the packet operation, $ filename is included in the package name. Because it cannot be a 1000 integer, you still need to perform this operation after the Read line jumps out.
Filenum = $ [filenum + 1]
Done
The basic process is as follows:
During execution, it is found that the file counter filenum is always restored to the default value.
After debugging, it is found that this occurs after each while read line loop file is completed.
When SH is started, two *. Sh processes with the same name are also found.
After reading the data, we found that there are two common usage methods in while read line.
CatFile |WhileRead lineDoDone
WhileRead lineDoDone<File
After testing, the following conclusions are obtained:
The method using pipeline | is equivalent to starting an independent sub-process. Therefore, the variable filenum in the loop belongs to the self-process, and the value of filenum outside the loop is different although it has the same name.
This phenomenon does not occur when the redirection <method is used. No sub-process occurs when the script is started. Therefore, the filenum variable inside the loop is in the same bash shell as the filenum variable outside the loop.
Variable scope in a while read line Loop