0

I haven't been able to find anything related to this nor can my professor explain what's going on. Below is the problem description:

After quite a bit of debugging following is the bash script to print odd or even:

echo $1
odd_even=$(echo "$1 % 2" | bc -l)
echo $odd_even

if [[ $odd_even -eq 0 ]]
then
echo "even"
else
echo "odd"
fi

Following is the output:

$ bash logic_ex2.sh 3
3
0
even

This is weird because the variable odd_even contains 0 while the argument is 3.

We ran the following command to check whats wrong with the echo "3 % 2" | bc -l construction since without using that construction we could get the script working:

$ echo "3 % 2" | bc -l
0

Then we ran bc in the terminal and ran 3 % 2 which gave 1 as the proper output.

Can somebody please explain what is happening here?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
jodobear
  • 1
  • 2

2 Answers2

1

Check this explanation as to bc -l calculates a % b differently from plain bc without the -l. The quick solution is to set your scale back to zero:

$ bc -l <<< "scale=0; 3 % 2"
1

But I would probably do this without using bc at all, since bash includes sufficient functionality to calculate integer remainders. If all you need is integer math, bash may be good enough on its own.

#!/usr/bin/env bash

echo "$1"
odd_even=$(($1 % 2))
echo "$odd_even"

if [[ $odd_even -eq 0 ]]; then
    echo "even"
else
    echo "odd"
fi

My results:

$ bash remtest.sh 3
3
1
odd
$ bash remtest.sh 4
4
0
even
ghoti
  • 45,319
  • 8
  • 65
  • 104
  • Thanks @ghoti that works! Your explanation of scale makes sense now. I was i was completely confounded by this, but now everything is clear. I would accept and upvote your answer but i don't have enough reputation.. – jodobear Oct 08 '18 at 23:41
0

another option:

#!/bin/bash
var=$1

if [[ $((var % 2)) -eq 0 ]];
   then echo "$var is even";
   else echo "$var is odd";
fi