2017-07-06 56 views
1

這是可能與source <(grep = test.ini)讀取來自.ini文件變量:有沒有辦法清除使用source <(grep = ...)讀取的變量?

$ 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命令添加和取消設置它們放在一起?

+1

是它允許重新使用ini文件? –

+3

這樣的'ini'文件可能不安全。 – anubhava

+0

爲什麼找到一個ini文件不安全? – alvas

回答

1
unset $(awk -F\= '/=/ { printf gensub(" ","","g",$1)" " }' test.ini) 

用awk創建變量的列表中設置,然後使用該輸出來運行未設置。我們使用gensub來擺脫被設置的變量周圍的空間。

+0

不要執行'printf $ field',總是執行'printf'%s「,$ field'。想象一下當'$ field'包含像'%s'這樣的printf格式化字符時的區別。由於gensub(),您還應該提及這是gawk特有的。 –

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 

因人而異,讀者要注意,等

+0

是否有「不同的米勒」的原因?任何示例? – alvas

+2

@alvas這是一個可怕的非強大的方法,我絕對沒有聲稱它只會正確地取消設置源文件時分配的變量,或者它將取消所有這些變量。因此免責聲明。 –

相關問題