Check if $REPLY is in a range of numbers
The [
command/shell builtin has comparison tests, so you can just do
if [ "$REPLY" -ge 1 ] && [ "$REPLY" -le 32 ]; then REPLY=-2;
elif [ "$REPLY" -ge 33 ] && [ "$REPLY" -le 48 ]; then REPLY=-1; fi
where -ge
means greater-or-equal-to (and so on). The [
command is just a command, not special syntax (it's actually the same as test
: check out man test
), so it NEEDS the space after it. If you write [$REPLY
it will try to find a command named [$REPLY
and execute it, which won't work. The same goes for closing ]
.
Here, we're using the &&
shell operator to run the second command only if the first is successful. [
also supports -a
to and two tests, but it's deprecated and its usage should be discouraged as it causes arguments not to be parseable reliably.
Edit: to test if the number is integer (if that can happen in your code), first do the test
if [[ "$REPLY" =~ ^[0-9]+$ ]]; then
existing code
else echo "$REPLY is not an integer" >&2 && exit 1; fi
Of course all these bracket expressions return 0 (true) or 1 (false) and can be combined. Not only you can put everything in the same bracket, you can also do
if [[ "$REPLY" =~ ^[0-9]+$ ]] && [ "$REPLY" -ge 1 ] && [ "$REPLY" -le 32 ]; then ...
or something similar.
You could simply say:
((REPLY>=1 && REPLY<=32)) && REPLY=-2
((REPLY>=33 && REPLY<=48)) && REPLY=-1
Quoting from the manual:
((...))
(( expression ))
The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic). If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to
let "expression"
You could do something like this:
#!/usr/bin/env bash
read -p "- Audio Quality [scale from -2 to 10] ? "
if [ -n "$REPLY" ] ; then
ABITRATE="-aq $REPLY"
fi
echo "You chose : $ABITRATE : $REPLY"
## If 0 < $REPLY < 33 and $REPLY is a number
if [[ "$REPLY" =~ ^[0-9]+$ && "$REPLY" -gt 0 && "$REPLY" -lt 33 ]]
then
echo "GOOD"
else
echo "BAD"
fi