I have this variable in an Ubuntu bash script and I am looking to extract its length:

var_names='test1 tutorial2 test3w'

In a Python list, I could do len(var_names) and the result would be 3. I need to do something similar in a bash script - I need to find a way to determine the length of the string and for the answer to be 3.

My attempt:

I tried to convert this into an array an then test its length:

echo ${#arr[@]}


echo $arr

only gives



Howe do I get the length of this variable in bash, such that the returned length is 3?

  • I'm confused - is the output of echo ${#arr[@]} not 3? if not, what is it? what is the relevance of the value of $arr (which is equivalent to ${arr[0]}, I think - i.e. it should be the first element of the array) – steeldriver Feb 14 '17 at 2:44
  • My thought with that approach was to convert it to an array and then determine its length. I didn't try echo ${#arr[@]} yet. I get $arr which only gave 1 element and left out the other 2. This is where I am stuck. – edesz Feb 14 '17 at 3:03
  • 1
    If you want to get the whole array, you can use "${arr[@]}"; if you want the lengths of the individual element strings, ${#arr[0]}, ${#arr[1]}, and ${#arr[2]} – steeldriver Feb 14 '17 at 3:08
  • @steeldriver Add an answer please. – heemayl Feb 14 '17 at 3:28

Your approach is correct,${#arr[@]} will give you the number of elements in the array (in this case, 3):

$ var_names='test1 tutorial2 test3w'
$ arr=($var_names)
$ echo ${#arr[@]}

You can also return the string lengths of the individual array elements using ${#arr[0]}, ${#arr[1]} and so on:

$ echo "${#arr[0]}"
$ echo "${#arr[1]}"
$ echo "${#arr[2]}"

The reason that $arr returns only the first element test1 is that it is equivalent to ${arr[0]}; if you want to return the whole array, you can use either ${arr[@]} or ${arr[*]}:

echo "${arr[@]}"
test1 tutorial2 test3w

See the Arrays section of man bash

  • Just what I was looking for. Thanks for the detailed explanation. – edesz Feb 14 '17 at 3:53

Since you are effectively trying to find number of words in the variable, you can use wc -w command for that:

$ var_names='test1 tutorial2 test3w'                                                                                     

$ wc -w <<< "$var_names" 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.