'What is the simplest way to get the length of a range or set of items in bash?
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?
Solution 1:[1]
# 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'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andreas Louv |
