Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign the result of echo to a variable in bash script

Tags:

linux

bash

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?

like image 584
Remco Avatar asked Dec 30 '15 15:12

Remco


People also ask

How do you assign an echo value to a variable in a shell script?

Also you need $() to run a command and don't need quotes on the right-hand side of an assignment. Also, shell variables are case sensitive. You can reduce your 2 sed commands to one: sed -e 's/,\|$/: chararray /g' -- that is, replace all commas or end of string with the replacement text.

How do you store output of echo in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do you assign a value to a variable in bash?

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter. Bash sees the space before “Geek” as an indication that a new command is starting.


1 Answers

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

like image 150
Ijaz Ahmad Avatar answered Sep 21 '22 06:09

Ijaz Ahmad