2

我有以下两个脚本:

“scr1.sh”

#!/bin/sh

func_in_scr1()
{

    echo func_in_scr1 var is $var


}

var=7645

func_in_scr1 &

( func_in_scr1 )

./scr2.sh

“scr2.sh”

echo in scr2 var is $var

这是输出:

  • func_in_scr1 var 是 7645
  • func_in_scr1 var 是 7645
  • 在 scr2 var 是

问题:

  1. 当 scr1.sh 中的函数在 bg 和 subshel​​l 中运行时,它能够访问 $var 的值。
  2. 但是 scr2.sh 无法访问 $var 的值。

我的印象是子进程(子进程)只能访问导出的变量而不能访问未导出的变量,所以我对 #1 感到特别惊讶。

有人可以解释这个结果吗?

4

1 回答 1

2

In these two cases:

func_in_scr1 &
( func_in_scr1 )

you start subshells. That is right that they are separate processes also but they see all variables of the parent shell (but of course you cannot give changes in this variables back; they are simple copies created during fork() of parent).

In this case

./scr2.sh

there is no subshell. You run a separate process. The parent shell knows nothing about it. Ant its has no other ability to give variables to him except exporting.

于 2012-06-19T07:15:28.530 回答