-1

I made this simple script where you're asked the dividend and the divisor, then it displays the quotient:

#!/bin/bash
read -p "Dividend? " dividend
read -p "Divisor? " divisor
    if [ $divisor = "0" ]
        then
            echo "∞"
    else
        echo "$((scale=4;$dividend / $divisor))" | bc
    fi

But if you type a divisor that doesn't equal to 0 this syntax error is shown:

./division.sh: line 8: scale=4;5 / 4: syntax error: invalid arithmetic operator (error token is ";5 / 4")

I don't know why this doesn't work, I saw in a thread this is the way you get decimals with bc. Anyone knows what's wrong? Thanks in advance.

1 Answers1

2

Since you are using bc for the calculation, there is no need to use the bash arithmetic expansion ( $((...)) ).
Furthermore, the syntax of your arithmetic expansion is wrong as ; is no arithmetic operator. Second, this method only can output integers.

The correct script would look like as follows.

#!/bin/bash
read -p "Dividend? " dividend
read -p "Divisor? " divisor
    if [ $divisor = "0" ]
        then
            echo "∞"
    else
        echo "scale=4;$dividend / $divisor" | bc
    fi
Thomas
  • 6,223
  • 1
    It might be a good idea to note that the "scale=x" parameter controls the precision of the output for those that don't know. – Elder Geek Mar 04 '17 at 12:14