在Bash中取消一个动态变量列表

时间:2017-12-04 20:03:43

标签: bash environment-variables

如何使用Bash实现以下目标:

np.array ([ True, [[5....]] ])

我基本上想要取消设置最初使用eval设置的变量。

2 个答案:

答案 0 :(得分:3)

您可以分叉子shell,在子shell中执行eval,一旦完成,退出子shell:

# do this in a subshell
(
x="search='something' replace='something' subject=/path"
eval "$x"
echo "search=$search"
)

# now out of subshell
echo "search=$search"

答案 1 :(得分:3)

序言:谨慎使用eval作为eval is evil ...
无论...

可以很快完成此任务:

unset ${x//=*([^ ])}

正如glenn jackman所指出的那样,只有在变量内容中没有空格时才能正常工作。

在这种情况下,我们可以(很快)准备一些中间变量( x without spaces ):

xwos=${x//\"*([^\"])\"}        # This will drop `search="don't know"`
xwos=${xwos//\'*([^\'])\'}     # This will drop `search='blah blah'`
unset ${xwos//=*([^ ])}

很好,将其添加到您的脚本中将完成这项工作:

xwos=${x//\"*([^\"])\"}; xwos=${xwos//\'*([^\'])\'}; unset ${xwos//=*([^ ])}

说明/展示

当然,您必须使用 extglob 的选项,如果尚未设置:

shopt -s extglob

让我们试试:

x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search 
something something

declare -p search replace subject
declare -- search="something something"
declare -- replace="something"
declare -- subject="/path/path"

shopt -s extglob
xwos=${x//\"*([^\"])\"}
printf 'X w/o double quoted spaces 1st:\n    "%s"\n' "$xwos"
X w/o double quoted spaces 1st:
    "search='something something' replace='something' subject=/path/path"

xwos=${xwos//\'*([^\'])\'}
printf 'X w/o single quoted spaces 2nd:\n    "%s"\n' "$xwos"
X w/o single quoted spaces 2nd:
    "search= replace= subject=/path/path"

printf 'String containing variables w/o values:\n    "%s"\n' "${xwos//=*([^ ])}"
String containing variables w/o values:
    "search replace subject"

unset ${xwos//=*([^ ])}

declare -p search replace subject
bash: declare: search: not found
bash: declare: replace: not found
bash: declare: subject: not found

Nota:如果您不再需要x,则可以重新定义x,而不是填充新变量:

shopt -s extglob;x=${x//\"*([^\"])\"};x=${x//\'*([^\'])\'};unset ${x//=*([^ ])}

演示

x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search 
something something

shopt -s extglob;x=${x//\"*([^\"])\"};x=${x//\'*([^\'])\'};unset ${x//=*([^ ])}
echo $search