Unix 在zsh中封装源代码脚本
我试图控制在zsh中寻找脚本时定义哪些变量。我在想象与此代码对应的东西:Unix 在zsh中封装源代码脚本,unix,posix,zsh,Unix,Posix,Zsh,我试图控制在zsh中寻找脚本时定义哪些变量。我在想象与此代码对应的东西: ( source variable_definitions somehow_export variable1=$variable_defined_in_script1 ) echo $variable1 因此,我希望在外部范围中定义variable1,而不是在脚本中定义variable\u或源脚本中的任何其他变量 (export在本例中是一个神奇的占位符,它允许将变量定义导出到父shell。我认为这是不可能的,
(
source variable_definitions
somehow_export variable1=$variable_defined_in_script1
)
echo $variable1
因此,我希望在外部范围中定义variable1
,而不是在脚本中定义variable\u
或源脚本中的任何其他变量
(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
和蔼可亲!简单又完美,谢谢你我打赌你已经想到了这一点,但是你有一个同样可以处理数组的解决方案吗?@MatthiasMichaelEngh-为数组等添加了一个示例。希望这有帮助!