1

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.

2
  • 1
    You can't create a python list in a bash script without using python, so I'm a little unclear as to what you are asking ... You could pass the string 1 10 100 1000 to a python script, parse it as a string, and split() it into a list, if that helps. Commented Aug 7, 2019 at 10:51
  • 1
    Why don't you just pass the array as a list of arguments to python? ./your-script.py "${b[@]}" and then read sys.argv in python? Commented Aug 7, 2019 at 11:00

3 Answers 3

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

2

You can try this:

echo "[${b[*]}]" | sed "s/ /, /g"

1 Comment

This will not work if Bash array elements contains space or strings
1

It would have too many ways too answer this question :

  1. If you have a list of items :

    my_list=(1, 10, 100, 1000); for i in $my_list; do echo $i; done
    
  2. If you would make loop in range numbers:

    for i in $(seq 1 20); do echo $i; done
    
  3. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.