Reputation: 7818
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!
Upvotes: 5
Views: 2355
Reputation: 19266
I guess the most efficient and elegant thing here would be to use readarray
in order to read the value into an array. That's if you're okay with using arrays, of course. You should be, but you never know. This would require the delimiter to be a newline, though. Anyhow :
readarray -t values < <(python file.py)
Will get you an array of one element for each line output by the python file.py
with the trailing newline removed. Check out man bash
for other options for this very cool builtin.
Upvotes: 1
Reputation: 2614
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
Upvotes: 1
Reputation: 206659
You can use something like this:
read var1 var2 < <(python file.py)
The funky <( )
syntax is called process substitution.
Upvotes: 7