可以使用.ini
从source <(grep = test.ini)
文件中读取变量:
$ cat test.ini
[head]
shoulders=/hahaha/
knees=/lololol/
toes=/kekeke/
$ source <(grep = test.ini)
$ echo $shoulders
/hahaha/
$ echo $knees
/lololol/
$ echo $toes
/kekeke/
我可以手动清除从source <(grep = ...)
命令读取的变量,例如
$ unset toes
$ echo toes
但有没有办法自动跟踪从source
命令添加哪些变量并将它们全部取消设置?
答案 0 :(得分:1)
unset $(awk -F\= '/=/ { printf gensub(" ","","g",$1)" " }' test.ini)
使用awk创建正在设置的变量列表,然后使用此输出运行unset。我们使用gensub来摆脱所设置变量周围的任何空格。
答案 1 :(得分:1)
通常情况下,这类事情非常不可靠。但你可以这样做:
set | grep -v ^_ > /tmp/original-vars # record variables
source <(grep = test.ini) # read from init file
# now, compare current variables assigned with the original and unset
# those that were not originally assigned while attempting
# to mask out some common internal variables that bash sets but making
# no claims at robustness or safety:
set | grep -v ^_ | diff -u - /tmp/original-vars \
| awk '/^-/ && NR>1{print $2}' FS=[=-] \
| while read var; do unset $var; done
YMMV,读者要小心,等等。