您可以让函数将变量作为第一个arg,然后使用要返回的字符串修改变量。#!/bin/bashset -xfunction pass_back_a_string() { eval "$1='foo bar rab oof'"}return_var=''pass_back_a_string return_varecho $return_var打印“ foo bar rab oof”。编辑:在适当的位置添加了引号,以允许字符串中的空格解决@Luca Borrione的评论。编辑:作为演示,请参阅以下程序。这是一个通用的解决方案:它甚至允许您将字符串接收到局部变量中。#!/bin/bashset -xfunction pass_back_a_string() { eval "$1='foo bar rab oof'"}return_var=''pass_back_a_string return_varecho $return_varfunction call_a_string_func() { local lvar='' pass_back_a_string lvar echo "lvar='$lvar' locally"}call_a_string_funcecho "lvar='$lvar' globally"打印:+ return_var=+ pass_back_a_string return_var+ eval 'return_var='\''foo bar rab oof'\'''++ return_var='foo bar rab oof'+ echo foo bar rab ooffoo bar rab oof+ call_a_string_func+ local lvar=+ pass_back_a_string lvar+ eval 'lvar='\''foo bar rab oof'\'''++ lvar='foo bar rab oof'+ echo 'lvar='\''foo bar rab oof'\'' locally'lvar='foo bar rab oof' locally+ echo 'lvar='\'''\'' globally'lvar='' globally编辑:这表明原始变量的值是在功能可用,进行了错误@Xichen李在评论批评。#!/bin/bashset -xfunction pass_back_a_string() { eval "echo in pass_back_a_string, original $1 is \$$1" eval "$1='foo bar rab oof'"}return_var='original return_var'pass_back_a_string return_varecho $return_varfunction call_a_string_func() { local lvar='original lvar' pass_back_a_string lvar echo "lvar='$lvar' locally"}call_a_string_funcecho "lvar='$lvar' globally"这给出了输出:+ return_var='original return_var'+ pass_back_a_string return_var+ eval 'echo in pass_back_a_string, original return_var is $return_var'++ echo in pass_back_a_string, original return_var is original return_varin pass_back_a_string, original return_var is original return_var+ eval 'return_var='\''foo bar rab oof'\'''++ return_var='foo bar rab oof'+ echo foo bar rab ooffoo bar rab oof+ call_a_string_func+ local 'lvar=original lvar'+ pass_back_a_string lvar+ eval 'echo in pass_back_a_string, original lvar is $lvar'++ echo in pass_back_a_string, original lvar is original lvarin pass_back_a_string, original lvar is original lvar+ eval 'lvar='\''foo bar rab oof'\'''++ lvar='foo bar rab oof'+ echo 'lvar='\''foo bar rab oof'\'' locally'lvar='foo bar rab oof' locally+ echo 'lvar='\'''\'' globally'lvar='' globally
上面的所有答案都忽略了bash手册页中所述的内容。在函数内部声明的所有变量将与调用环境共享。所有声明为local的变量将不会共享。范例程式码#!/bin/bashf(){ echo function starts local WillNotExists="It still does!" DoesNotExists="It still does!" echo function ends}echo $DoesNotExists #Should print empty lineecho $WillNotExists #Should print empty linef #Call the functionecho $DoesNotExists #Should print It still does!echo $WillNotExists #Should print empty line并输出$ sh -x ./x.sh+ echo+ echo+ f+ echo function starts function starts+ local 'WillNotExists=It still does!'+ DoesNotExists='It still does!'+ echo function ends function ends+ echo It still 'does!' It still does!+ echo同样在pdksh和ksh下,此脚本也可以实现!