BASH If conditional always returns "True" [duplicate] - bash

This question already has answers here:
How do I do if statement arithmetic in bash?
(5 answers)
When are square brackets required in a Bash if statement?
(3 answers)
Closed 2 years ago.
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

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

Related

How to only accept input that is a valid index of an array in bash [duplicate]

This question already has answers here:
Why should there be spaces around '[' and ']' in Bash?
(5 answers)
Difference between single and double square brackets in Bash
(7 answers)
Why is "[[ 10 < 2 ]]" true when comparing numbers in bash? [duplicate]
(1 answer)
Closed 6 months ago.
I am trying some simple input validation in bash. Basically this part of my script outputs "press [index] to select [array element]." However I cannot seem to get it to stop and exit gracefully when an invalid input is entered. From my research so far this SHOULD work:
declare -a scenarios=()
scenarios+=("Scenario_123")
scenarios+=("Scenario_456")
scenarios+=("Scenario_789")
for i in ${!scenarios[#]}; do
echo -e "select $i for ${scenarios[$i]}"
done
read ScenInd
echo ${#scenarios[#]} #[${ScenInd}=~^[0-9]+$, =~ ^[[:digit:]]+
if ! [${ScenInd}=~ ^[[:digit:]]+$ ] || [${ScenInd} < 0] || [${ScenInd} >= ${#scenarios[#]}];
then
echo "INVALID SELECTION"
exit
fi
but when I run it and enter 8, I get '[8=~: command not found'
What have I done wrong and how do I fix this? I have tried this both with [${ScenInd}=~^[0-9]+$ and =~ ^[[:digit:]]+ yet the results are the same.
Thanks in advance

Why two numbers not summarized in script? [duplicate]

This question already has answers here:
How do I echo a sum of a variable and a number?
(9 answers)
How can I do basic maths in bash?
(4 answers)
How do I print the result of a command with 'echo'?
(1 answer)
Closed 4 years ago.
I am newer in bash.
I try to create script that summarizetwo numbers:
Here is script:
echo "the result is:" expr $1+$2
Here how I call the script:
./scr3 50 98
And here is result that I get after the script executed:
the result is: expr 50+98
While I get the the string with two summarized numbers I expect to get the summarize of two numbers.
My question is why I don't get the result of summarize of the two numbers?
Why? Because echo prints its arguments, and you're passing expr as an argument.
A best-practice alternative would be:
echo "The result is: $(( $1 + $2 ))"
...though the a smaller change (albeit to very inefficient code; expr is an artifact of the 1970s, made irrelevant with the introduction of $(( )) in the 1992 POSIX sh standard, and should never be used in new development) is simply:
echo "The result is: $( expr "$1" + "$2" )"

Bash Script "integer expression expected" , use of floats in bash instead of other language [duplicate]

This question already has answers here:
How can I compare two floating point numbers in Bash?
(22 answers)
Closed 6 years ago.
I am new to bash scripting. My code is :
MK=M
SM=1.4
if [[ $MK == "M" ]]
then
if [ $SM -gt 1.3 ]
then
echo "Greater than 1.3M"
else
echo "Less than 1.3M"
fi
else
echo "Not yet M...."
fi
Reply:
/tmp/tmp.sh: line 6: [: 1.4: integer expression expected
Less than 1.3M
What am i doing wrong ?
Here's what man bash says:
arg1 OP arg2 ... Arg1 and arg2 may be positive or negative integers.
You seem to be trying to compare floating point numbers.
It's ultimately because bash is not terribly patient when it comes to floating point numbers. In very simple terms here, I would suggest you do one of two things:
It looks like you are trying to determine if something is larger than 1.3 Mb or not, is this correct? If this is the case, then leave everything the way you have it, and just use Kb for $sm and the compare
like this:
#/bin/bash
mk="p"
km="p"
sm="1400"
ms="1300"
if [[ $mk == $km ]]
then
if [ $sm > $ms ]
then
echo "Greater than 1.3M"
else
echo "Less than 1.3M"
fi
else
echo "Not yet M...."
fi
or
Use bc for the calculation of the floating point numbers...
# /bin/bash
mk="p"
km="p"
sm="1.4"
ms="1.3"
if [ $(echo "$mk == $km" | bc) ]
then
if [ $(echo "$sm > $ms" | bc) ]
then
echo "Greater than 1.3M"
else
echo "Less than 1.3M"
fi
else
echo "Not yet M...."
fi
One more thing to note here, is that, as you can see from my code, I have primed new variables with the data, rather than using raw letters and numbers in boolean and compare operations, which can have some genuinely unexpected results. Also, while they may work in some conditions, temporarily, bash prefers all variable names to be in lower-case. Let me know if you have any questions.. However, I have tested both code chunks, and they both work fine.

input vs variable comparison isn't working? [duplicate]

This question already has answers here:
How do I compare two string variables in an 'if' statement in Bash? [duplicate]
(12 answers)
Closed 6 years ago.
Here is a random number generator followed by a line clear timer and you are then to try and input the number that you saw. I cant seem to set up the comparison between the randNum variable and the input. I tried setting a defined value for the input as well and still receive an error "command not found" when checking input vs randNum variable
n=$RANDOM$RANDOM$RANDOM; let "n %= 10000000000";
echo $n
for i in {5..1}; do echo $i; sleep 1; tput cuu1; tput el; done
tput cuu1; tput el
echo "what was that number?"
#read input
input=999999999
if [$input == $n]
then
echo "you are correct"
else
echo "you are incorrect"
fi
Shells need spaces around brackets [ and ] when used for this purpose (replacement syntax for the test command), and you should better use -eq instead of == for numeric comparison:
if [ $input -eq $n ]
If you use the arithmetic comparison, rather than the old testcommand (a.k.a. [) then you can avoid these issues. Spaces here are less important inside the brackets:
if (( input == n ))
Note that the leading $ is not required (and using it can cause issues)

For loop range in Bash [duplicate]

This question already has answers here:
Sequences expansion and variable in bash [duplicate]
(7 answers)
Closed 7 years ago.
Im trying a code in bash to generate prime nos as follows:
#!/bin/bash
echo "Enter till where u wish to generate"
read num
echo "Generating prime numbers from 2 to $num"
flag="prime"
for i in {2..$num}
do
for j in {2..$((${num}-1))}
do
[ $((${i}%${j})) -eq 0 ] && flag="nprime" || flag="prime"
break
done
[ "$flag" == "prime" ] && echo "$i"
done
Upon execution, it throws an error because the for loop takes the sequence mentioned in the curly braces as it is not as a sequence.
Could you guide me as to where am i going wrong ?
man bash in my version says:
A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer.
You can't use variables in ranges. Try seq instead:
for i in $(seq 2 $num) ; do
Note that incr for seq goes between x and y.
Use:
for ((i=2; i<=$num; i++))

Resources