You can map a value into a range,
and then use the index number of that range in a case statement:
cmil_limits=(320 404 510 642)
index=0
for limit in "${cmil_limits[@]}"
do
if [ "$cmils" -lt "$limit" ]
then
break
fi
((index++))
done
case "$index" in
0) # < 320
cawg="??"
;;
1) # 320-403
cawg="25 AWG"
;;
2) # 404-509
cawg="24 AWG"
;;
3) # 510-641
cawg="23 AWG"
;;
4) # > 641
cawg="??"
;;
esac
If $cmils is less than 320,
we break out of the for loop on its first iteration, with index=0.
If $cmils is ≮ 320 (i.e., is ≥ 320),
we increment index (→1) and go on to the next iteration.
Then, if $cmils is < 404 (i.e., ≤ 403, assuming that it is a whole number),
we break out of the loop with index=1.
And so on.
If $cmils is ≮ 642, it is ≥ 642 and hence > 641,
so we run to the end of the for loop and get index=4.
This has the advantages that it keeps the cutoff values together,
all on the same line, and you don’t have to maintain redundant numbers
(e.g., your current code, and that of one other answer, lists
both 403 and 404, and both 509 and 510 — which is redundant,
and more work to maintain if the numbers ever change.
I don't know whether this is real-world concern.)
cmil_limits is an array.
bash, ksh, and some other shells support arrays, but some others do not.
If you need to do something like this in a shell that doesn’t support arrays,
you can just put the list directly into the for statement:
for limit in 320 404 510 642
do
︙
or use the shell’s parameter list as an array:
set -- 320 404 510 642
for limit in "$@"
do
︙
Some shells let you abbreviate the above:
set -- 320 404 510 642
for limit
do
︙
((…)) arithmetic is also a bashism (as is the let statement).
If you need to do something like this in a shell
that doesn’t support ((…)) arithmetic,
you can replace the
((index++))
statement (to increment index) with
index=$(expr "$index" + 1)
Note that the spaces before and after the + are required.
caseis the right tool for this" —honestly, the right tool for this is to use something other than Bash. Bash isn't really a programming language. It's extremely valuable for what it is, but numerical calculations should be done in other ways. And no, you can't usecasefor numerical comparisons in Bash. – Wildcard Aug 08 '17 at 02:05elifchains is simplest, but it's not a great illustration of what Bash is really for. Nor is it something that I would want to see in production code.) – Wildcard Aug 08 '17 at 02:15