1

Why can't I do this simple arithmetic operation and store it in a variable in bash shell? I've been struggling with this and playing around with () and $ symbols but no luck.

read t
let r=$(5/9)*$($t-32)

I get a: let: r=*: syntax error: operand expected (error token is "*")

2 Answers 2

4

When you are using the let statement, you don't need the dollar-sign, but single-quote the expression instead to keep the shell preprocessor from messing with your operators. Note that bash does not seem to be able to handle numbers which aren't integers, so the (5/9) expression will always be zero. Try the second let statement.

read -p 'Temp in Fahrenheit (no decimals): ' t

# let r='(5/9)*(t-32)' -- this doesn't work
let r='5*(t-32)/9'

echo "Centigrade: $r"
1
  • 1
    it doesn't work because bash only performs integer arithmetic, and 5/9 evaluates to 0 -- do the multiplication first before the division. Commented Oct 11, 2012 at 23:18
2

Try that :

read -p 'Type integer temp (Fahrenheit) >>> ' int
echo "$(( 5 * ( int - 32 ) / 9 )) Celcius"
1

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