Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
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? –  Levon Jul 9 '12 at 12:23
2  
@Levon maybe his favorite language is bash :) –  rush Jul 9 '12 at 12:32
1  
@rush touché .. :-) –  Levon Jul 9 '12 at 12:34
add comment

2 Answers

up vote 7 down vote accepted

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

share|improve this answer
    
This is a terrible plan. It is not a theoretical security hole, it is a massive and very real security crater. –  Alex Chamberlain Jul 9 '12 at 19:57
add comment

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
share|improve this answer
    
Just eval 'a=100 ...' (without the echo) works as well –  daniel kullmann Jul 9 '12 at 13:49
1  
Of course, I was emulating the output of his program there. –  lynxlynxlynx Jul 9 '12 at 14:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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