Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a variable with a variable minus a constant in a linux shell script?

Tags:

linux

bash

shell

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

like image 257
Marc Avatar asked Nov 07 '13 13:11

Marc


3 Answers

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.

like image 143
devnull Avatar answered Sep 28 '22 07:09

devnull


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 ([[ ... ]]).

like image 33
Jo So Avatar answered Sep 28 '22 08:09

Jo So


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
like image 41
chepner Avatar answered Sep 28 '22 08:09

chepner