How to store the length of a string in a variable

2019-03-02 20:28发布

I am using this guide as a reference.

I am able to run the command to find the length of a string, say

expr length 'monkey brains'

which returns 13 as expected

However I am having trouble with storing the result in a variable, say a variable called hi. First I tried straight up assigning hi

hi=expr length 'monkey brains'

which gave a command not found error. My thought process was then to wrap the command all in a string and then use $ to evaluate the string. So what I have is

hi="expr length 'monkey brains'"
echo $($hi)

but this didn't work either - expr: syntax error

Does anyone know what else I could try here or why my approach doesn't work?

2条回答
The star\"
2楼-- · 2019-03-02 20:51

I think this is what you're trying to do.

$ expr length 'monkey brains'
13

To store the output to a variable using command substitution:

$ len=$(expr length 'monkey brains'); echo "$len"
13

You can also do this using parameter expansion in bash:

$ string='monkey brains'; len=${#string}; echo "$len"
13

Both the Bash Hackers Wiki and the Bash Guide are good resources for information.

查看更多
▲ chillily
3楼-- · 2019-03-02 20:51

You may try this

hi="monkey brains"
echo -n $hi | wc -c
查看更多
登录 后发表回答