The cause of variable assignment loss caused by MPs queue used in shell script

Source: Internet
Author: User
This problem was discovered when the SGE startmpi. Sh script was transformed. Consider the following shell code:
#! /Bin/sh
# Declare-I

Testline = "Hello :"

Cat testfile | while read line; do
Testline = "$ {testline }$ {Line }"
Echo "in cycle, the testline is: $ testline"

# For (I = 0; I <3; I ++) do
# Testline = "$ {testline }$ {I }"

# I = 0
# While [$ I-lt 3]; do
# Testline = "$ {testline }$ {I }"
# I = $ I + 1

Done
Echo $ testline

 

The testfile used in the code can be any text file, for example:


Phy2 2 2
Phy3 2
Phy4 2

In this case, the code running result is unexpected. The testline variable in the while loop is like it has not been assigned a value. The output is as follows:

In cycle, the testline is: Hello: phy2 2
In cycle, the testline is: Hello: phy2 2 phy3 2
In cycle, the testline is: Hello: phy2 2 phy3 2 phy4 2
Hello:

Why? Refer to the code above. If you comment out the cat testfile | while read line; do section, open the for loop section, or open the while loop section, testline can be assigned values in the loop, and the final echo $ testline is correct. Why?

The final error is the pipeline operator |. The reason is very simple. I learned the principle of Shell Command Execution before learning shell, which also describes the pipeline. To put it simply, using the pipe symbol in shell will generate subshell, so that the value assignment to the variable in this subshell takes effect only in subshell, and will not affect the process of the shell script itself.

However, KSh now has a feature, which can reflect the variable assignment in the pipeline to the parent shell. This is why some people on the internet ask that such code is OK in K shell.

I have attached an article I found on the Internet to explain it well.

/Files/super119/bash_pipe_variable_lost.mht.zip

Related Article

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.