0

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:

arr=($var_names)
echo ${#arr[@]}

however:

echo $arr

only gives

test1

Question:

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

4
  • 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) Feb 14, 2017 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, 2017 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]} Feb 14, 2017 at 3:08
  • @steeldriver Add an answer please.
    – heemayl
    Feb 14, 2017 at 3:28

2 Answers 2

2

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[@]}
3

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

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

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

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

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" 
3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .