Variable scope in a while read line Loop

Source: Internet
Author: User
Tags variable scope

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.