Get External variable contents in shell while

Source: Internet
Author: User
Tags stdin

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

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.