Anthony
Anthony

Reputation: 35988

How to read array from stdout in bash

I am executing a python script from my bash script. The python script outputs 4 lines to stdout. I would like to store the output of these 4 lines in 4 different variables in bash or one array with 4 elements.

When I run my python script byitself I see the 4 lines on stdout:

$ python my_script.py
line1
line2
line3
line4

In my bash script I've done this:

OUTPUT="$(python my_script.py)"

echo "${OUTPUT}"

readarray -t y <<<"$OUTPUT" 

After above when I do echo $y I only see output of first line (line1).

How can I use the output of python script as 4 variables or an array?

Upvotes: 1

Views: 1524

Answers (2)

Hast
Hast

Reputation: 44

Do you have bash as the primary parser or have the bash shabang. This because sh doesn't have this nice array handling...

But if you have why not create the bash array when you run the python script by the array creation parentheses? And then use Johns way to print them.

OUTPUT=( $(python my_script.py) )
echo "len of OUTPUT=${#OUTPUT[@]} and the data is:" ${OUTPUT[@]}
echo "Second entry is=" ${OUTPUT[1]}

... ...

Upvotes: -1

John Kugelman
John Kugelman

Reputation: 361984

$y is the first element of the array. ${y[@]} will give you all of them.

echo "${y[@]}"

Upvotes: 2

Related Questions