脚本中bash shell脚本和函数的变量范围

 敖军士 发布于 2023-02-05 08:58

关于函数,变量范围和可能的子shell,我对我的脚本有点困惑.我在另一篇文章中看到管道产生子shell,而父shell无法从子shell访问变量.在反引号中运行cmds的情况是否相同?

为了不让人厌烦,我缩短了我的100多行剧本,但我试图记住留下重要的元素(即反引号,管道等).希望我没有遗漏任何东西.

global1=0
global2=0
start_read=true

function testfunc {
   global1=9999
   global2=1111
   echo "in testfunc"
   echo $global1
   echo $global2
}

file1=whocares
file2=whocares2

for line in `cat $file1`
do
   for i in `grep -P "\w+ stream" $file2 | grep "$line"`   # possible but unlikely problem spot
   do
         end=$(echo $i | cut -d ' ' -f 1-4 | cut -d ',' -f 1)   # possible but unlikely spot
         duration=`testfunc $end`       # more likely problem spot
   done
done

echo "global1 = $global1"
echo "global2 = $global2"

因此,当我运行我的脚本时,最后一行显示global1 = 0.但是,在我的函数testfunc中,global1设置为9999并且调试消息打印出函数内至少为9999.

这里有两个问题:

    反引号是否会产生一个子shell,从而使我的脚本不起作用?

    我该如何解决这个问题?

在此先感谢您的帮助.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有