【问题标题】:Is there a way to clear the variables read using source < (grep = ...)?有没有办法清除使用 source < (grep = ...) 读取的变量?
【发布时间】:2017-12-10 06:00:37
【问题描述】:

可以使用source &lt;(grep = test.ini).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 &lt;(grep = ...) 命令读取的变量,例如

$ unset toes
$ echo toes

但是有没有办法自动跟踪从source 命令添加的变量并将它们全部取消设置?

【问题讨论】:

  • 是否允许重复使用ini文件?
  • 像这样在ini 文件中获取资源可能不安全。
  • 为什么获取 ini 文件不安全?
  • 可以,重复使用ini文件就可以了。

标签: bash shell unix grep unset


【解决方案1】:
unset $(awk -F\= '/=/ { printf gensub(" ","","g",$1)" " }' test.ini)

使用 awk 创建正在设置的变量列表,然后使用此输出运行未设置的变量。我们使用 gensub 去除被设置的变量周围的任何空格。

【讨论】:

  • 永远不要使用printf $field,而是始终使用printf "%s", $field。想象一下$field 包含像%s 这样的 printf 格式字符时的区别。由于 gensub(),您还应该提到这是 gawk 特有的。
【解决方案2】:

通常,这种事情非常不可靠。但你可以这样做:

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,读者当心,等等。

【讨论】:

  • “变化米数”有什么原因吗?有什么例子吗?
  • @alvas 这是一种非常不可靠的方法,我绝对没有声称它只会正确地取消设置在获取文件时分配的那些变量,或者它会取消所有这些变量。因此免责声明。
猜你喜欢
  • 2016-01-06
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 2022-01-19
  • 1970-01-01
  • 2011-05-18
相关资源
最近更新 更多