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?
echo ${#arr[@]}
not3
? 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)echo ${#arr[@]}
yet. I get$arr
which only gave 1 element and left out the other 2. This is where I am stuck."${arr[@]}"
; if you want the lengths of the individual element strings,${#arr[0]}
,${#arr[1]}
, and${#arr[2]}