How do I get size of an array string in the shell script?

1

I have a string that I pass as a parameter, for example:

 "2,3,4,5"

To get every item of it I do:

#!/bin/bash

for ((i=1; i<=4; i++))
do
        echo "$1" | cut -d "," -f $i
done

But I would like to make the loop iterate up to the maximum length of the string (which is variable), where each value separated by a comma is an item. So how can I count the number of items to insert into for ?

Example: For "2,3,4,5" you have 4 items.

    
asked by anonymous 14.09.2018 / 20:00

1 answer

3

You do not really need the size, just use tr to change the comma to \n and scroll through the result with for :

for i in $(echo "2,3,4,5" | tr "," "\n")
do
    echo $i
done

This prints:

2
3
4
5

In fact, only the echo "2,3,4,5" | tr "," "\n" command already prints the numbers the way you need it. for would only be necessary if you need to do anything else with the numbers. If you only need to print them, one per line, you do not even need for .

If you also need the quantity, just count the lines generated by tr , using wc (with the -l option, which returns only the number of lines):

n=$(echo "2,3,4,5" | tr "," "\n" | wc -l)

In this case, the value of $n will be 4 .

PS: The syntax of $( comando ) is called Command Substitution .     

14.09.2018 / 20:12