Multiple conditions in if statement

I am doing a basic question for adding, product, subsraction, division by taking user input in first and second I don’t understand where am I going wrong because it’s not passing any test case.

constraints:-
-100<=x,y<=100,
y != 0

read -p "enter first number:" first
read -p "enter second number:" second
if [[ ("$first" -ge "-100"  -a "$first" -ge "100") -a ("$second" -ge "-100" -a "$second" -ge "100") ]]
then
    if [ $second -ne 0 ]
    then    
        echo "$first + $second" | bc
        echo "$first - $second" | bc
        echo "$first * $second" | bc
        echo "$first / $second" | bc
    fi
fi
'''
Asked By: Prince

||

Don’t use the obsolete -a operator and parentheses to do logical AND between tests. Instead use && between several [ ... ] tests:

if [ "$first"  -ge -100 ] && [ "$first"  -le 100 ] &&
   [ "$second" -ge -100 ] && [ "$second" -le 100 ] &&
   [ "$second" -ne    0 ]
then
    # your code here
fi

The above also shows the correct tests to ensure that both the first and second variables are in the range (-100,100) and that the second variable is not zero.

Since you don’t mention what shell you’re using, I have converted the non-standard [[ ... ]] tests into standard [ ... ] tests.

If you’re using bash you could alternatively use either

if [[ $first  -ge -100 ]] && [[ $first  -le 100 ]] &&
   [[ $second -ge -100 ]] && [[ $second -le 100 ]] &&
   [[ $second -ne    0 ]]
then
    # your code here
fi

or, with arithmetic expansions,

if (( first  >= -100 )) && (( first  <= 100 )) &&
   (( second >= -100 )) && (( second <= 100 )) &&
   (( second !=    0 ))
then
    # your code here
fi

You may also chain multiple AND tests with && within [[ ... ]] and (( ... )).

You additionally don’t need four separate invocations of bc. One is enough:

for op in '+' '-' '*' '/'; do
    printf '%s %s %sn' "$first" "$op" $second"
done | bc
Answered By: Kusalananda
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.