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?
42 Answers
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
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