"Piping" values into Bash variables
Asked Answered
T

3

5

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!

Technics answered 1/3, 2012 at 16:44 Comment(0)
T
7

You can use something like this:

read var1 var2 < <(python file.py)

The funky <( ) syntax is called process substitution.

Telemachus answered 1/3, 2012 at 16:48 Comment(2)
This is a lot better than my awk nonsense below.Yezd
@Mat: Works fantastically. Thanks!Technics
Y
1

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

Yezd answered 1/3, 2012 at 16:48 Comment(0)
K
1

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.

Kolnick answered 1/3, 2012 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.