Bash – How to parse many variables to bash

bashscripting

A program outputs its data in this format:

n=4607356
null_cells=5668556
cells=10275912
min=0.0433306089835241
max=0.53108499199152
range=0.487754383007996
mean=0.40320252333736
mean_of_abs=0.40320252333736
stddev=0.0456556814489487
variance=0.00208444124856788
coeff_var=11.3232628285782
sum=1857697.565113524
first_quartile=0.378443
median=0.410276
third_quartile=0.435232
percentile_90=0.457641

And I want parse some of those variables into bash so I can use them into my script eg:

$n = 4607356
$median = 0.410276

and so on, in one go.

How can I do that?

Best Answer

Seems the easiest way is to redirect output to a file and then to source this file.

In script it will look like:

#!/bin/sh
program > tmp_file
. tmp_file
rm tmp_file
echo $any_var_you_need

In bash you can do it without temporary file at all:

#!/bin/bash
source <(program)
echo $any_var_you_need

The only theoreticall security hole is that program may output some dangerous code that will destroy something.

You can avoid it with checking program's output with sed to be sure it contents only variables:

program | sed '/^\s*[a-zA-Z_.][_a-zA-Z0-9]*=[a-zA-Z0-9_-+.,]*/!d;s/ .*//;'

it will remove all strings that seems like not variables (may be edited at your taste).

Related Question