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