18

I'm a Linux newbie and have copied a bash script that extracts values from a XML. I can echo the result of a calculation perfectly, but assigning this to a variable doesn't seem to work.

#!/bin/bash
IFS=$'\r\n' result=(`curl -s "http://xxx.xxx.xxx.xxx/smartmeter/modules" | \
xmlstarlet sel -I -t -m "/modules/module" \
    -v "cumulative_logs/cumulative_log/period/measurement" -n \
    -v "point_logs/point_log/period/measurement" -n | \
sed '/^$/d' `)

# uncomment for debug
echo "${result[0]}"*1000 |bc 
gas=$(echo"${result[0]}"*1000 |bc)

echo "${result[0]}"*1000 |bc

Gives me the result I need, but I do not know how to assign it to a variable.

I tried with tick marks:

gas=\`echo"${result[0]}"*1000 |bc\`

And with $(

Can somebody point me in the right direction?

metropolision
  • 405
  • 4
  • 10
Remco
  • 183
  • 1
  • 1
  • 5

2 Answers2

22

If you want to use bc anyway then you can just use back ticks , why you are using the backslashes? this code works , I just tested.

  gas=`echo ${result[0]}*1000 | bc`

Use one space after echo and no space around * operator

Ijaz Ahmad
  • 11,198
  • 9
  • 53
  • 73
  • 3
    `$( ...)` and backticks are both forms of command-substitution. Backticks are only for systems that don't have `$(..cmd..)`. Join the 1990's and start using the "new" form of command-substitution! ;-) Good luck to all. – shellter Dec 30 '15 at 16:37
  • 1
    You are welcome , you can execute any command like that within backtiks and assign the result to a variable – Ijaz Ahmad Dec 30 '15 at 19:34
9

There is no need to use bc nor echo. Simply use the arithmetic expansion $(( expression )) for such operations:

gas=$(( ${result[0]} * 1000))

This allows the evaluation of an arithmetic expression and the substitution of the result.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • I get the error `syntax error: invalid arithmetic operator (error token is ".533 * 1000")` I read that bash script variables are problematic with float? – Remco Dec 30 '15 at 18:14
  • @Remco yes, arithmetic expansion is just on integers. – fedorqui Dec 30 '15 at 22:16
  • 1
    @fedorqui : FWIW, `echo $(( .533 * 1000 ))` works in ksh93+. I thought maybe it was the dbl-quotes visible in Remco's error msgs, but `".533 * 1000"` works in ksh too ;-/ ! Good luck to all. – shellter Jan 01 '16 at 03:41
  • @shellter I remember doing some investigation some time ago and yes, from `ksh93` floating-point arithmetic is available. From [Learning the korn shell](http://docstore.mik.ua/orelly/unix3/korn/ch06_02.htm), _While expr and ksh88 were limited to integer arithmetic, ksh93 supports floating-point arithmetic. As we'll see shortly, you can do just about any calculation in the Korn shell that you could do in C or most other programming languages._ – fedorqui Jan 01 '16 at 22:06