cod*_*ard 5 arrays bash associative-array escaping
我有一个 bash 脚本,它使用文件名作为关联数组中的键。一些文件名中有引号,我似乎找不到任何方法来取消它们。
这是从终端复制问题的示例:
$ declare -A x
$ y="key with spaces"
$ z="key with spaces and ' quote"
$ x[$y]=5 # this works fine
$ x[$z]=44 # as does this
$ echo "${x[$y]}" "${x[$z]}" # no problems here
5 44
$ unset x["$y"] # works
$ unset x["$z"] # does not work
bash: unset: `x[key with spaces and ' quote]': not a valid identifier
$ echo "${x[$y]}" "${x[$z]}" # second key was not deleted
44
Run Code Online (Sandbox Code Playgroud)
在我的脚本中处理的文件名是任意的,无论它们包含什么字符都需要工作(在合理范围内,至少需要使用可打印的字符。) unset 用于清除具有某些属性的文件上的标志。
当它们可能包含引号时,如何让 bash 取消设置这些特定键?
lny*_*yng 13
我发现这对我有用:
unset 'x[$z]'
Run Code Online (Sandbox Code Playgroud)
这适用于其他特殊字符:
$ y="key with spaces"
$ v="\$ ' \" @ # * & \`"
$ x[$y]=5
$ x[$v]=10
$ echo ${x[*]}
5 10
$ unset 'x[$v]'
$ echo ${x[*]}
5
Run Code Online (Sandbox Code Playgroud)