The code for the script is:

echo "Years:"
read age
x=`expr $age*365`
echo -e $x

The output when I call this script from the command line is as follows:


(say I put 20)


Why is it not evaluating?


we should escape the special character * and keep spaces between values and operator.

Try as,

x=`expr $age \* 365`

expr is archaic and largely obsolete these days. It's also very limited and clumsy to use compared to better alternatives like:

  1. bash has integer-only arithmetic built-in these days.

    $ age=20
    $ echo "$((age * 365))"
    $ x=$((age*365))
    $ echo "$x"
  2. use bc for floating-point arithmetic:

    $ age=20
    $ echo "$age * 365.25" | bc

    Or, if you want to drop the decimal fraction:

    $ echo "scale=0; $age * 365.25/1" | bc

    The division by 1 is needed because addition, subtraction, and multiplication ignore the scale setting in bc. This is a long-standing annoyance and is unlikely to be "fixed".

  3. if you prefer RPN, you could use dc:

    $ age=20
    $ dc -e "$age 365.25 * p" 

Note: backticks are obsolete and deprecated too. Use $(...) instead of backticks. e.g.

x=$(echo "$age * 365.25" | bc)

x=$(dc -e "$age 365.25 * p")
  • It's not that other operators ignore scale, it's that for other operators, maximum scale can be determined, while for division, you have to impose an arbitrary limit and the scale variable is used for that. 1/3 needs an infinite number of digits after the radix for instance, so you need choose where to stop. – Stéphane Chazelas Sep 25 '19 at 6:46
  • The practical effect of that, though, is that you're going to get a trailing .00 or whatever on the result of any operation that doesn't involve a division, no matter what you set scale to. – cas Sep 25 '19 at 6:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.