0

The code I wrote to solve a challenge keeps giving me a response of "True" and I have no idea why. I've played with the syntax and keep getting "True", so there's probably something I'm not understanding about the way Bash works.

I apologize if this is too simple or if there are similar questions out there. I looked but don't know how to phrase the issue.

The test values input are n=3 x=3 y=4 (says true, should be false) and n=12 x=3 x=4 (does not reach this point of the test.

#!/bin/bash

read n
echo "n is " $n

read x
echo "x is " $x

read y
echo "y is " $y

if [[ ((n%x==0 && n%y==0)) ]]; then
    echo "true"
else
    echo "false"
fi
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • This is checking whether `((n%x==0` and `n%y==0))` are empty strings. They never are, so always true. `((` is recognized by the parser in a general context, but not inside the [conditional expression](https://wiki-dev.bash-hackers.org/syntax/ccmd/conditional_expression). – Charles Duffy Mar 28 '20 at 18:05
  • BTW, keep your parameter expansions inside quotes. `echo "n is $n"`, not `echo "n is" $n`; doesn't make a big difference here, but it will in a context where those values might contain characters in IFS or double as globs; see [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo). – Charles Duffy Mar 28 '20 at 18:07
  • (It's also a good habit to use the `-r` argument to `read` unless you have a specific reason to do otherwise; `read -r x` and `read -r y` do less munging/transformation of the user's input before assigning it to the named variables). – Charles Duffy Mar 28 '20 at 18:10

1 Answers1

1

Get rid of the unnecessary [[]]. Your new if statement would look like if ((n%x==0 && n%y==0)).

Aplet123
  • 33,825
  • 1
  • 29
  • 55