LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   BASH : how to act based on test against a range of numbers (https://www.linuxquestions.org/questions/programming-9/bash-how-to-act-based-on-test-against-a-range-of-numbers-461328/)

hollywoodb 07-05-2006 06:44 PM

BASH : how to act based on test against a range of numbers
 
alright, I can set a file or a variable with a range of numbers...

for example: (either way is fine by me)

Code:

$ cat range.txt
63
88
99

$ echo $RANGE
63 88 99

I have a test number

Code:

$ echo $TEST
77

I want to run a command when the first number in $RANGE is greater than $TEST, and then stop the test on $RANGE. I DO NOT want the command to run on any number in $RANGE other than the first number greater than $TEST.

for example, (using static numbers for example, and keeping in mind that $TEST is 77 in this example)

Quote:

63 > $TEST (false, do nothing)
88 > $TEST (true, run command)
99 > $TEST (true, do nothing, since first correct conditional already meant and command already run)
or

Quote:

63 > $TEST (false, do nothing)
88 > $TEST (true, run command, and stop testing $RANGE vs $TEST)

unSpawn 07-05-2006 07:13 PM

Code:

test="77"; range=($(cat range.txt)); for i in $(seq 0 $[${#range[@]}-1]); do
 [ "${range[$i]}" -gt "$test" ] && ( echo "running command"; break ) ; done


spirit receiver 07-06-2006 03:51 AM

Code:

(while read && [[ $REPLY -lt $(( $test + 1 )) ]]; do true; done; echo "\"$REPLY\" is the first number greater than $test or the last line." ) < range.txt
Edit: It seems like the brackets around 'echo "running command"; break' are causing trouble in unSpawn's suggestion (because they are forking a subshell)? See
Code:

while true; do (break); done
But the following works as desired:
Code:

test="77"; range=($(cat range.txt)); for i in $(seq 0 $[${#range[@]}-1]); do
 [ "${range[$i]}" -gt "$test" ] && echo "running command" && break; done


unSpawn 07-06-2006 05:10 AM

Thanks for cleaning up again spirit receiver. I would prefer this below over "&&" since I'm not interested if echo fails or not, but that would be even less then trivial:
Code:

[ "${range[$i]}" -gt "$test" ] && { echo "running command"; break; }; done

spirit receiver 07-06-2006 06:09 PM

Quote:

Originally Posted by unSpawn
I'm not interested if echo fails or not

You're right, even if "echo" is not likely to fail, it seems reasonable to use your syntax in a situation where "echo" is replaced with a command that might fail.


All times are GMT -5. The time now is 05:02 PM.