Reputation: 1267
I would like to convert a bash array like echo ${b[*]}
that outputs something like 1 10 100 1000
to a list format in Python: [1, 10, 100, 1000]
that can be ready to use by a Python program. I need to do the conversion in a bash script.
I was doing it with for and if checking the positions, but wondering if there's something cleaner. Thx.
Upvotes: 1
Views: 1588
Reputation: 19665
The correct way to do it is:
#!/usr/bin/env bash
my_list=(1 10 100 1000 "alpha" "beta")
s=''
printf '['
for e in "${my_list[@]}"; do
if [[ "$e" = $((e)) ]]; then
q=''
else
q='"'
fi
printf '%s%s%s%s' "$s" "$q" "$e" "$q"
s=', '
done
printf ']\n'
Turns Bash array:
(1 10 100 1000 "alpha" "beta")
Into Python array:
[1, 10, 100, 1000, "alpha", "beta"]
Upvotes: 2
Reputation: 105
It would have too many ways too answer this question :
If you have a list of items :
my_list=(1, 10, 100, 1000); for i in $my_list; do echo $i; done
If you would make loop in range numbers:
for i in $(seq 1 20); do echo $i; done
If you would return exactly power of ten:
for i in $(seq 0 3); do echo $((10**i)); done
At the end I think your script would be third one, I hope it would be good to you.
Upvotes: 1