2

How would one go about comparing a variable, lets say

Var1

to a range of numbers such as 0-5. If Var1 is in that range then the statement will return true, else will print an error or exit.

3
  • How are you being given this range? Commented Mar 23, 2014 at 19:37
  • Var1 will be given through stdin, basically if the user doesnt input 1,2,3,4 or 5 through stdin then it will just print an error Commented Mar 23, 2014 at 19:41
  • So just test if it's greater than 0 and less than 6? Commented Mar 23, 2014 at 19:43

1 Answer 1

2

In simple terms, you can just test the variable passed while running the script:

#!/bin/bash

if (( 0 <= $1 && $1 <= 5 )); then
    echo "In range"
else
    echo "Not in range"
fi

Pass the number to the script and it will test it against your range. For example, if the above it put in a script called check.sh then:

$ bash check.sh 10
Not in range
$ bash check.sh 3
In range

You can make the script executable to avoid using bash ... whenever you need to run the script. The $1 used above the is the first parameter passed to the script. If you don't like to use positional variables, then you can save it a variable inside the script if you wish.

Sign up to request clarification or add additional context in comments.

2 Comments

+1. Purely as a matter of style, I write (( 0 <= $1 && $1 <= 5 )) -- that's closest to math notation a ≤ x ≤ b
Thanks @glennjackman. Actually, I like that style. Will use that from now on. Makes it more readable too. Thank you. Will update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.