将源脚本封装在 zsh 中

encapsulate sourced script in zsh

我试图控制在 zsh 中获取脚本时定义哪些变量。我在想象对应于这段代码的东西:

(
  source variable_definitions

  somehow_export variable1=$variable_defined_in_script1
)
echo $variable1

因此,我希望 variable1 在外部范围内定义,而不是 variable_defined_in_script 或源脚本中的任何其他变量。

somehow_export 在这个例子中是一些神奇的占位符,它允许将变量定义导出到父 shell。我认为这是不可能的,所以我正在寻找其他解决方案)

是这样的吗?

(
  var_in_script1='Will this work?'

  print variable1=$var_in_script1
) | while read line
do
    [[ $line == *=* ]] && typeset "$line"
done

print $variable1
#=> Will this work?

print $var_in_script1
#=> 
# empty; variable is only defined in the child shell

这使用 stdout 向父级发送信息 shell。根据您的要求,您可以将文本添加到 print 语句以仅过滤您想要的变量(这只是查找“=”)。


如果需要处理数组等更复杂的变量,typeset -p 是 zsh 中的一个很好的选择,可以提供帮助。它对于简单打印也很有用 变量的内容和类型。

(
  var_local='this is only in the child process'

  var_str='this is a string'

  integer var_int=4

  readonly var_ro='cannot be changed'

  typeset -a var_ary
  var_ary[1]='idx1'
  var_ary[2]='idx2'
  var_ary[5]='idx5'

  typeset -A var_asc
  var_asc[lblA]='label A'
  var_asc[lblB]='label B'

  # generate 'typeset' commands for the variables
  # that will be sent to the parent shell:
  typeset -p var_str var_int var_ro var_ary var_asc

) | while read line
do
    [[ $line == typeset\ * ]] && eval "$line"
done

print 'In parent:'
typeset -p var_str var_int var_ro var_ary var_asc

print
print 'Not in parent:'
typeset -p var_local

输出:

In parent:
typeset var_str='this is a string'
typeset -i var_int=4
typeset -r var_ro='cannot be changed'
typeset -a var_ary=( idx1 idx2 '' '' idx5 )
typeset -A var_asc=( [lblA]='label A' [lblB]='label B' )

Not in parent:
./tst05:typeset:33: no such variable: var_local