Home > database >  What is the simplest way to get the length of a range or set of items in bash?
What is the simplest way to get the length of a range or set of items in bash?

Time:01-28

I have a situation where I might specify a for loop range using either

  • a range "{1..10}" e.g. length = 10
  • or a set of items "tcp udp" e.g. length = 2

What is the simplest way to get the length of that set?

CodePudding user response:

In both cases, create an array:

$ x=({1..10})
$ y=(tcp udp)

then use parameter expansion to get the number of elements in the array.

$ echo "${#x[@]}"
10
$ echo "${#y[@]}"
2

CodePudding user response:

# Bash, as brace expansion are not POSIX
count=0
for _ in {1..10}; do ((count  )); done
echo "$count" # 10

# POSIX compliant
count=0
for _ in tcp udp; do : $((count=count 1)); done
echo "$count" # 2

But neither of these things makes sense, as if you know the values beforehand then you would also know the count.

If you have an array in bash, then you can simply read the length:

arr=({1..10})
echo "${#arr[@]}" # 10

arr=(tcp udp)
echo "${#arr[@]}" # 2

Or if you have a file, or a list of matches from eg. grep then either using wc -l or grep -c would work:

$ my_cmd | wc -l
$ my_cmd | grep -c 'pattern'
  •  Tags:  
  • Related