读书人

请问Solaris脚本的赋值有关问题

发布时间: 2012-02-22 19:36:56 作者: rapoo

请教Solaris脚本的赋值问题
我的脚本如下:

#!/bin/sh
TAG=no
if [ -f /tmp/tmp.ini ];then
while read OPTNAME EQSIGN OPTVALUE
do
if [ $OPTNAME = 'TAG' ]; then
TAG=$OPTVALUE
echo $TAG
break
fi
done < /tmp/tmp.ini
fi

echo $TAG

我的文件tmp.ini里面内容如下:
TAG = yes

脚本运行的结果是
yes
no

也就是说,在循环体里面TAG的值已经被赋为yes了, 但是这个值并没有被保存,离开循环体之后,TAG的值还是初始化的no
这是什么原因呢?

顺便说一下,如果仅仅是while结构,这个值是可以被保存下来的,也就是说增加了读取文件的操作,产生了这样的问题,请教高人!

谢谢!




[解决办法]
奇怪,我在ubuntu上执行时两个yes,难道solaris有差异?
[解决办法]
换个shell试试

#!/bin/ksh
[解决办法]
这个好像是Solaris上的Sh的一个特性,当While/until/loop有输入输出重定向的时候,它会新开一个子Shell来执行而且里面定义或者改变变量对父进程无效.

用man sh看一下说明就会发现有这么个Note:

If the input or the output of a while or until loop is
redirected, the commands in the loop are run in a sub-shell,
and variables set or changed there have no effect on the
parent process:

lastline=
while read line
do

SunOS 5.10 Last change: 2 May 2008 26

User Commands sh(1)

lastline=$line
done < /etc/passwd
echo "lastline=$lastline" # lastline is empty!

楼主还是换个写法或者用其它Shell吧。

读书人网 >其他服务器

热点推荐