unix - 将源脚本封装在 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。根据您的要求,您可以在打印语句中添加文本以过滤您想要的变量(这只是寻找一个'=')。
如果您需要处理更复杂的变量,例如数组,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
推荐阅读
- r - 使用数字在 MAC 上写入和打开 xlsx 文件
- perl - 为什么从@_ 转移的值不是别名?
- python - 用 Pandas 合并两个不同的数据框
- android - 通过 BLE 从 MAXREFDES100 存储数据
- jquery - 列表子元素上的框阴影行为
- r - 反向过滤并计算多列上的多个数字
- ruby-on-rails - 您如何通过 Clearance 和 Pundit 邀请其他用户加入“团队”或“帐户”或“项目”?
- c++ - C++ - For 循环有时不会停止 - 多线程
- javascript - 如何使用javascript获取动态表中的单元格值
- sql-server - SQL 查询性能调优 - 附加执行计划