Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my Shell code always return Even, even if number is odd

I am using this code to check if user’s input (which is always number) is even or odd, but the script always return "Even"

read -p "Enter a number: " x
if ((x % 2 == 0));
   then echo "Even"; 
   else echo "Odd"; 
fi

I am using this test:

def solution(x)
  puts("Number: #{x}")
  run_shell(args: [x]).strip
end

describe "Solution" do
  it "should print 'Even' for even numbers" do
    [0, 2, 4, 78, 100000, 1545452, -2, -10, -123456]
      .each { |x| expect(solution(x)).to eq('Even') }
  end
  
  it "should print 'Odd' for odd numbers" do
    [1, 3, 5, 77, 100001, 1545455, -1, -3, -9, -12345]
      .each { |x| expect(solution(x)).to eq('Odd') }
  end
end

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your Ruby code passes arguments on the shell script’s command line, but the shell script is looking for arguments on its standard input stream.

Because in an arithmetic context the shell treats an empty string like a 0, you get a result of always-even.

Consider reading from stdin only when you haven’t been provided input on the command line:

#!/usr/bin/env bash

if [[ $1 ]]; then
  x=$1
else
  read -p 'Enter a number: ' x
fi

if ((x % 2 == 0)); then
  echo "Even"
else
  echo "Odd"
fi
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading