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

Cla*_*ied 9 unix linux bash shell

关于函数,变量范围和可能的子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"
Run Code Online (Sandbox Code Playgroud)

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

这里有两个问题:

  1. 反引号是否会产生一个子shell,从而使我的脚本不起作用?
  2. 我该如何解决这个问题?

在此先感谢您的帮助.

dam*_*ois 3

你可以尝试类似的东西

global1=0
global2=0
start_read=true

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

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
         testfunc $end       # more likely problem spot
   done
done

echo "global1 = $global1"
echo "global2 = $global2"
Run Code Online (Sandbox Code Playgroud)