1

My calculator generates the error mentioned in the title when I try to use the operator "/" as well as the numbers 4.5 and 2.

This is (just like the error states) most likely due to what's after the decimal point in 4.5, but I don't know how I could fix this and why the script actually manages to give me the correct result afterwards.

Code:

#!/bin/bash

read -p "Operator: " operator
read -p "First number: " ch1
read -p "Second number: " ch2

case $operator in
 "+") echo "scale=2; $ch1+$ch2" | bc -l;;
 "/") if [[ $ch1 -eq 0 || $ch2 -eq 0 ]]
       then
        echo "Nope..."
       else
        echo "scale=2; $ch1/$ch2" | bc -l
      fi
      ;;
esac

Full output:

./script2.sh: line 9: [[: 4.5: syntax error: invalid arithmetic operator (error token is ".5")
2.25
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ayygurl
  • 11
  • 1
  • 3

1 Answers1

1

Despite producing floating point results, Bash does not support other type of arguments than integers, so you need to rather invoke external tools like bc for your math or stick to integers only.

See the Bash documentation, section "6.5 Shell Arithmetic":

The shell allows arithmetic expressions to be evaluated, as one of the shell expansions or by using the (( compound command, the let builtin, or the -i option to the declare builtin.

Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141