首页 > 解决方案 > 将源脚本封装在 zsh 中

问题描述

我试图控制在 zsh 中获取脚本时定义的变量。我在想象与此代码相对应的东西:

(
  source variable_definitions

  somehow_export variable1=$variable_defined_in_script1
)
echo $variable1

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

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

标签: unixposixzsh

解决方案


像这样的东西?

(
  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。根据您的要求,您可以在打印语句中添加文本以过滤您想要的变量(这只是寻找一个'=')。


如果您需要处理更复杂的变量,例如数组,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

推荐阅读