Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash test value evaluation

Tags:

bash

shell

I am learning about shell scripting, particularly the shell commands test, [ ]. [[ ]] and (( )), I wrote a real simple script to test my understanding, it takes in three arguments, if all three are integers (and the second argument is lower than the third) it tests if the first argument lays in the range between the second and third. Here it is:

#!/bin/bash
#test if arg1 is contained in the range [arg2, arg3]

function isint()
{
    if [[ "$1" =~ ^-?[0-9]+$ ]]; then
    echo $1 is integer
    return 0
    else
    echo $1 is not integer
    return 1
    fi
}


if [[ $(isint $1) && $(isint $2) && $(isint $3) &&  $2 -lt $3  ]]; then
    if [[ $2 -le $1  &&  $1 -le $3 ]]; then
    echo "$1 is in the range [$2,$3]"
    else
    echo "$1 is not in the range [$2,$3]"
    fi
else
    echo usage: $0 INT1 INT2 INT3
fi

Here is my problem: the preceding script doesn't work, the

if [[ $(isint $1) && $(isint $2) && $(isint $3) &&  $2 -lt $3  ]] 

never evaluates to true, if I want to obtain the wanted result I need to change the test to:

if [[ !$(isint $1) && !$(isint $2) && !$(isint $3) &&  $2 -lt $3  ]]

I don't get why this is working, the way I understood the testand [[ ]] commands is that they both evaluate the expressions passed to them, 0 evaluates to true and 1 evaluates to false. In my case if the correct parameters are passed to the script, the isint calls evaluate to 0, hence true, why the need for inverting them for the script to work as I want ?

Thank you in advance.

like image 455
ColdCoffeeMug Avatar asked Sep 21 '26 22:09

ColdCoffeeMug


1 Answers

Your issue is the $() enclosing your calls to isint. These replace the command with the standard output of the call to isint, so in this case what you're really running is:

if [[ "$1 is integer" && "$2 is integer" && "$3 is integer" &&  $2 -lt $3  ]] 

You want to use the return values instead, so just drop the $() and move the isint's out of the brackets:

if isint "$1" && isint "$2" && isint "$3" &&  [[ "$2" -lt "$3"  ]]

I added some quotes as well: you really should have your arguments quoted throughout the whole thing.

like image 169
Chris Avatar answered Sep 27 '26 22:09

Chris