5

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?

3
  • Those are a lot of variables, are you sure that writing a small Python (or pick your favorite scripting language) would not be an easier way to deal with all this data? Commented Jul 9, 2012 at 12:23
  • 2
    @Levon maybe his favorite language is bash :) Commented Jul 9, 2012 at 12:32
  • 1
    @rush touché .. :-) Commented Jul 9, 2012 at 12:34

2 Answers 2

7

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).

1
  • This is a terrible plan. It is not a theoretical security hole, it is a massive and very real security crater. Commented Jul 9, 2012 at 19:57
2

With the same security caveat as @rush mentioned, you could simply prepend eval to your command. Of course, in both cases, anything that isn't valid bash syntax will produce an error (that you can ignore).

Example:

$ echo 'a=1
> b=2
> c=1234'
a=1
b=2
c=1234
$ echo $b

$ eval echo 'a=1
b=2
c=1234'
a=1
$ echo $b
2
2
  • Just eval 'a=100 ...' (without the echo) works as well Commented Jul 9, 2012 at 13:49
  • 1
    Of course, I was emulating the output of his program there. Commented Jul 9, 2012 at 14:17

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.