First, the question
The question is simple, look at the following section of tmp.sh code:
#!/bin/Shx= "This was theinitial value of x" while a read line; Do x= "$line" = $x
/tmp/tmp's Content
1,a
Execute./tmp.sh, the normal x variable is the blue "1,a", but the actual result is the red part:
[Email protected] ~]$./1,aThis is theinitial value of x
The problem is obviously that the variable x is not brought outside after it has been modified in the while, why?
Second, the answer
After several searches, finally found the cause of the problem: because the child process is started, and the variable x after the child process has been modified, did not bring into the parent process. The original text reads as follows:
This was because in the Bourne shell redirected control structures run in a subshell, so the value of x only gets Chang Ed in the for non-Bourne shells are to use redirectioninstead of the pipeline
How to solve?
1. General Method:
# !/bin/shx="This was theinitial value of x"while aread line; Do x="$line" $x</tmp/ $x
Run:
[Qiu.li@l-tdata1.tkt.cn6 ~]$./tmp. 1,a1,a
2. Some elegant solutions:
#!/bin/shx="This is the initial value of x"exec 3<&0 #Save stdinexec</tmp/tmp while ReadLine Dox=$lineEcho$x Doneexec 0<&3 #Restore stdinecho x =$x
My English is really limited, the reason can only be posted in English:
#!/bin/sh at the top of a script doesn ' t guarantee you ' re using the Bourne shell. Some Systems link/bin/sh to Some the other shell. Check your system documentation to find out what the shell you ' re really getting in the this case.
Probably said: Note The top #!/bin/sh if you use the other this script cannot run. However, in some systems/bin/sh are assigned to the other shell interpreter, there is a different result. Detailed reference: http://www.cnblogs.com/liqiu/p/4107948.html
Get External variable contents in shell while