免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1680 | 回复: 4
打印 上一主题 下一主题

变量赋值问题,大家看看 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-06-01 12:25 |只看该作者 |倒序浏览
两个程序,变量name的输出结果不同,大家给诊断一下
#!/bin/bash
declare -i a=1
declare name=""
while [ $a -le 5 ]; do
        echo $a
        a=a+1
        name="neil"
done
echo $name
echo $a

name输出是: neil

#!/bin/bash
declare -i a=1
declare name=""
cat /tmp/db | while read line; do
        echo $a
        a=a+1
        name="neil"
done
echo $name
echo $a
其中,/tmp/db只有两行,
name输出为空

论坛徽章:
0
2 [报告]
发表于 2007-06-01 12:54 |只看该作者
环境变量 + sub shell

论坛徽章:
1
荣誉会员
日期:2011-11-23 16:44:17
3 [报告]
发表于 2007-06-01 13:33 |只看该作者
while read line;do
....
done<filename

论坛徽章:
0
4 [报告]
发表于 2007-06-01 23:10 |只看该作者
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.

论坛徽章:
0
5 [报告]
发表于 2007-06-06 14:54 |只看该作者
谢谢lgfang啦,说的够详细
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP