1

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:

Years: 

(say I put 20)

20*365

Why is it not evaluating?

0

2 Answers 2

3

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))"
    7300
    
    $ x=$((age*365))
    $ echo "$x"
    7300
    
  2. use bc for floating-point arithmetic:

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

    Or, if you want to drop the decimal fraction:

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

    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" 
    7305.00
    

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")
2
  • 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. Commented Sep 25, 2019 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. Commented Sep 25, 2019 at 6:59
1

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

Try as,

x=`expr $age \* 365`

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.