- 论坛徽章:
- 0
|
comp.unix.shell 的 FAQ
33. Why do I lose the value of global variables that are set in a loop.
Given the following program
#!/bin/sh
x="this is the initial value of x"
cat dataFile | while read line;do
x="$line"
done
echo x = $x
You may get the following for output
x = this is the initial value of x
This is because in the Bourne shell redirected control structures
run in a subshell, so the value of x only gets changed in the
subshell, and is lost when the loop ends.
In other shells the same result may be seen because of the way
pipelines are handled. In shells other than ksh (not pdksh) and
zsh elements of a pipeline are run in subshells. In ksh and zsh,
the last element of the pipeline is run in the current shell.
An alternative for non-Bourne shells is to use redirection
instead of the pipeline
#!/bin/sh
x="this is the initial value of x"
while read line;do
x="$line"
done < dataFile
echo x = $x
With a Bourne shell you need to reassign file descriptors, so no
pipline or redirection in the loop is involved.
exec 3<&0 # save stdin
exec < file
while read line; do
x=$line
done
exec 0<&3 # restore stdin
Note that putting #!/bin/sh at the top of a script doesn't
guarantee you're using the Bourne shell. Some systems link /bin/sh
to some other shell. Check your system documentation to find out
what shell you're really getting in this case. |
|