1

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?

Community
  • 1
  • 1
committedandroider
  • 8,711
  • 14
  • 71
  • 126

2 Answers2

4

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.

I0_ol
  • 1,054
  • 1
  • 14
  • 28
2

You may try this

hi="monkey brains"
echo -n $hi | wc -c
Hasan Rumman
  • 577
  • 1
  • 6
  • 16