作为参数传递的字符串的错误替换

Bad substitution for string passed as argument

我正在编写一个脚本,该脚本有时需要计算字符串的长度以在其周围绘制一个框。我不能使用 wc -c 来达到这种效果,因为我会将它用于非 ASCII 字符(遗憾)。我也避免使用 bashims 以获得最大的兼容性。

我正在使用 shell 的内置字符串长度计算器:

string="string"
echo ${#string}
# 6
string="stríñg"
echo ${#string}
# 6

到目前为止一切顺利,但现在当我将其作为参数传递时...

_function () {
  string_length=$(${#""})
}
# line 21: ${#""}: bad substitution

打印 $string_length 也没有显示任何内容。

我做错了什么?

string_length=${#1}

变量是1,所以</code>或<code>得到变量的值。然后${#1}得到1展开后的长度