0

我正在创建一些 shell 脚本。 script1在方法 1 中有一个 if 条件,用于 ex-

script1
method1()
{
 if [[somecondition]]
 then
     var=y
 else
     var=n
 fi
}
method2
....

....

我想在 script2 中有 var 的值

script2
methodx()
{
 foo=$var
 if [[ $foo = [Yy] ]]
 then
     .....
     .....
 elif [[ $foo = [Nn] ]]
 then
     .....
     .....
 else
     .....
 fi
}

这两个脚本都在另一个脚本中执行

script3

methodA()
{
./script1
....
....
....
}

methodB()
{
 ./script2
 ....
....
....
}

如何从script1to获取 var 的值script2

4

3 回答 3

0

As l0b0 says, in methodA, instead of just ./script1, you do:

foo=$( ./script1 )

you might want to put quotes around it if script1's output has spaces:

foo="$( ./script1 )"

Also, just to be safe, declare foo outside of method1 so it is global (which is the default but its always nice to see things declared. So, at the top of script3 do:

typeset foo

If you can incorporate script1 and script2 into script3, that will be faster and probably easier to maintain but there is still many times that you need to use the $( ... ) construct. In the old days, this use to be back tics:

foo=` ./script1 `

That syntax is still supported.

于 2013-06-20T11:44:48.723 回答
0

你总是需要内部空间[[]]. 此外,要测试您可以使用的模式[[ $foo =~ [Nn] ]]

通常,如果您想将脚本打印的文本存储到您使用的标准输出varname=$(command arguments)中。

于 2013-06-19T08:58:20.513 回答
0

看起来您需要method1从 script1 和methodxfrom script2 在 script3 的外壳中定义。为此,在 script3 中您需要source script1and source script2,而不是执行它们。为此,您可能需要稍微重构代码,因为我看到在 script1 和 script3 中都定义了 method1

于 2013-06-19T09:53:57.870 回答