I'm writing a script that, at one point, needs to compute the length of a string to draw a box around it. I can't use wc -c
for that effect because I will use it for non-ASCII characters (sad). I'm also avoiding bashims for maximum compatibility.
I'm using the shell's built-in string length calculator:
string="string"
echo ${#string}
# 6
string="stríñg"
echo ${#string}
# 6
So far so good, but now when I pass it as an argument...
_function () {
string_length=$(${#"$1"})
}
# line 21: ${#"$1"}: bad substitution
Priting $string_length
doesn't show anything as well.
What am I doing terribly wrong?
It's
string_length=${#1}
The variable is 1
, so $1
or ${1}
get's the value of the variable. Then ${#1}
get's the length of 1
after expansion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.