Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Piping" values into Bash variables

I have a Python script that outputs two numbers like so: 1.0 2.0 (that's a space in between the numbers, but it can be a \t, or whatever. I want a bash variable to save the 1.0, and another variable to save the 2.0. Is this possible?

In the past, I've only "piped" one value into a variable like so:

var=`python file.py` ;

but now, I'm interested in saving two values from the python file. Conceptually, similar to:

var1,var2=`python file.py` ; 

Any advice / help?

Thanks!

like image 930
Amit Avatar asked Mar 01 '12 16:03

Amit


2 Answers

You can use something like this:

read var1 var2 < <(python file.py)

The funky <( ) syntax is called process substitution.

like image 75
Mat Avatar answered Oct 07 '22 21:10

Mat


The one-liner I use for splitting fields is

 ... | awk '{print $1}' | ... # or $2, $3, etc.

so you could do

var = `foo`
var1 = `echo "$var" | awk '{print $1}'`
var2 = `echo "$var" | awk '{print $2}'`

edit: added quotes around $var

like image 30
zmccord Avatar answered Oct 07 '22 20:10

zmccord