I want to compare a variable with another variable minus a constant in a linux shell script.
In cpp this would look like this:
int index = x;
int max_num = y;
if (index < max_num - 1) {
// do whatever
} else {
// do something else
}
In the shell i tried the following:
index=0
max_num=2
if [ $index -lt ($max_num - 1) ]; then
sleep 20
else
echo "NO SLEEP REQUIRED"
fi
I also tried:
if [ $index -lt ($max_num-1) ]; then
...
if [ $index -lt $max_num - 1 ]; then
...
if [ $index -lt $max_num-1 ]; then
...
but non of these versions works. How do you write such a condition correctly?
Regards
The various examples that you tried do not work because no arithmetic operation actually happens in any of the variants that you tried.
You could say:
if [[ $index -lt $((max_num-1)) ]]; then
echo yes
fi
$(( expression ))
denotes Arithmetic Expression.
[[ expression ]]
is a Conditional Construct.
Portably (plain sh
), you could say
if [ "$index" -lt "$((max_num-1))" ]; then
echo yes
fi
Short version
[ "$index" -lt "$((max_num-1))" ] && echo yes;
[
is the test
program, but requires the closing ]
when called as [
. Note the required quoting around variables. The quoting is not needed when using the redundant and inconsistent bash extensions cruft ([[ ... ]]
).
In bash
, a more readable arithmetic command is available:
index=0
max_num=2
if (( index < max_num - 1 )); then
sleep 20
else
echo "NO SLEEP REQUIRED"
fi
The strictly POSIX-compliant equivalent is
index=0
max_num=2
if [ "$index" -lt $((max_num - 1)) ]; then
sleep 20
else
echo "NO SLEEP REQUIRED"
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With