I have a bash script that is calling a python script like so:
OUTPUT=$(python /path/path/script.py attr attr attr);
The python script will return a data list like so:
[item1, item2, item3]
How can I convert the $OUPUT variable which is a string of the return python data list into a bash array?
I'd like to read each item in bash if possible.
Add ()
and | tr -d '[],'
:
OUTPUT=($(python /path/path/script.py attr attr attr | tr -d '[],'))
echo ${OUTPUT[0]}
echo ${OUTPUT[1]}
echo ${OUTPUT[2]}
echo ${OUTPUT[@]}
Output:
item1
item2
item3
item1 item2 item3
You can make your script.py print a string that separates each item with spaces, which Bash will convert to an array, or you can use Bash to convert the return value of the python script into the format you want.
If you chose to print a string from your script.py you can use the following python code:
returnList = [1, 2, 3]
returnStr = ''
for item in returnList:
returnStr += str(item)+' '
print(returnStr)
In this case, the output of the following bash script:
OUTPUT=$(python /path/to/script.py)
echo $OUTPUT
for i in $OUTPUT;
do
echo $i
done
is:
1 2 3
1
2
3
Hope this helps you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With