尝试递增关联数组元素时出现错误的数组下标错误 [英] Bad array subscript error when trying to increment an associative array element

查看:82
本文介绍了尝试递增关联数组元素时出现错误的数组下标错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以创建一个关联数组,并为其中包含单引号的键分配一个整数:

I can create an associative array and assign an integer to a key that contains a single quote in it:

$ declare -A dict
$ var="john's"
$ dict[$var]=1
$ echo ${dict[$var]}
1
$ declare -p dict
declare -A dict=(["john's"]="1" )

但是当我尝试增加其值时:

But when I try to increment its value:

$ (( dict[$var]++ ))
bash: ((: dict[john's]++ : bad array subscript (error token is "dict[john's]++ ")
$ (( dict["$var"]++ ))
bash: ((: dict[john's]++ : bad array subscript (error token is "dict[john's]++ ")
$ (( dict["${var}"]++ ))
bash: ((: dict[john's]++ : bad array subscript (error token is "dict[john's]++ ")

我总是遇到相同的错误.我在做什么错了?

I always get the same error. What am I doing wrong?

推荐答案

key名称中的单引号使解析器将其视为未终止的引号字符.解决此问题的一种方法是转义键中的'字符

The single quote in key name is causing the parser to treat it as a un-terminated quote character. One way to fix this would be to escape the ' character in the key

key="john's"
printf -v escKey "%q" "$key"

现在由于%q指示符, printf() 会将必需的转义符应用于所有shell元字符,即使其成为"shell引用"且可重复使用.如果打印escKey的内容,您会发现'转义了

now because of the %q specifier, printf() would have applied required escapes to all shell meta characters i.e. making it "shell-quoted" and re-usable. If you print the contents of escKey you'll notice the ' escaped

printf '%s\n' "$escKey"
john\'s

现在,您可以在关联数组中使用此键名.请记住,您始终可以手动添加可能会造成混乱的转义符.由于%q是Shell提供的一种本机方式,因此使用它非常安全.

Now you can use this keyname in your associative array. Remember you can always manually add the escapes which could be messy. Since %q is a native way provided by the shell, it is much safe to use it.

(( dict["$escKey"]++ ))

也为bash版本> = 4.4 参数扩展具有@Q,这是printf()%q指定符的快捷方式,您可以使用

Also in bash versions >= 4.4 parameter expansion has @Q which is a shortcut for %q specifier of printf() using which you can do

(( dict["${key@Q}"]++ ))

这篇关于尝试递增关联数组元素时出现错误的数组下标错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆