简体   繁体   中英

Comparing a variable to a range of numbers in BASH

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM