函数求值时,Bash全局变量未更改
我想调用函数“B”,并将另一个函数名(A1、A2等)传递给它,该名称将从它调用。在这个传递名称的函数中,我初始化了几个变量,但是我不能从“B”函数中读取它们函数求值时,Bash全局变量未更改,bash,shell,Bash,Shell,我想调用函数“B”,并将另一个函数名(A1、A2等)传递给它,该名称将从它调用。在这个传递名称的函数中,我初始化了几个变量,但是我不能从“B”函数中读取它们 function A1 { echo "func 1" result1="a1" return 0 } function A2 { echo "func 2" anotherResult="a2" #..some other initialization return 0 } #..
function A1
{
echo "func 1"
result1="a1"
return 0
}
function A2
{
echo "func 2"
anotherResult="a2"
#..some other initialization
return 0
}
#...
function B
{
output=`$1` # $1 - function name
echo output=$output
echo result1=$result1 # <--- ERROR! result1 is empty!
}
B "A1" # main script runs function B and passes other function name
功能A1
{
回显“功能1”
结果1=“a1”
返回0
}
功能A2
{
回声“功能2”
另一个结果=“a2”
#…其他一些初始化
返回0
}
#...
功能B
{
输出=`$1`#$1-函数名
回波输出=$output
echo result1=$result1#函数B不调用A1
请注意,output=$($1)
不会执行您期望的操作,因为在$(…)
中运行的任何内容都将在不同的进程中执行,并且当该进程终止时,您设置的值将不再可访问
因此:
将执行您期望的操作,但将在文件系统上使用tempfile
。您的函数B不调用A1
请注意,output=$($1)
不会执行您期望的操作,因为在$(…)
中运行的任何内容都将在不同的进程中执行,并且当该进程终止时,您设置的值将不再可访问
因此:
将执行您期望的操作,但将在您的文件系统上使用tempfile
。output=$1
带反引号,不带反斜杠,末尾的B“A1”是bash code tooutput=$1
带反引号,不带反斜杠和B“A1”最后是bash代码tooI需要函数写入output=func 1 result1=a1当我调用output=`1`-变量output已初始化,但result1未初始化。我不能调用函数$1两次,因为它运行大约一分钟。是的,谢谢,这很有效!我想我必须编写类似output=“eval$1”的东西或者exec$1我需要函数写入output=func 1 result1=A1当我调用output=`1`-变量output已初始化,但result1未初始化。我不能调用函数$1两次,因为它运行大约一分钟。是的,谢谢,这很有效!我想我必须编写类似output=“eval$1”或exec$1的内容
function B
{
output=\`$1\` # <-- this will not call the $1 but will only print it
output=`$1` # <-- ( $($1) is a better style ) - will call whatever
# inside $1, but in another process
$1 # <-- here is the missing call in the current process.
...
}
function B
{
$1 > tempfile
read output < tempfile
echo output=$output
echo result1=$result1
}