1

I have a python list as a string with the following structure:

var="["127.0.0.1:14550","127.0.0.1:14551"]"

I would like to turn the string into a bash array to be able to loop through it with bash:

for ip in ${var[@]}; do

something

done
3
  • 1
    Welcome to Stack Overflow. SO is a question and answer page for professional and enthusiast programmers. Please add your own code to your question. You are expected to show at least the amount of research you have put into solving this question yourself. Commented Dec 10, 2020 at 16:25
  • 1
    I don't understand the question. How do you expect a python variable to be used in a bash script? The two contexts are completely separate. Commented Dec 10, 2020 at 16:28
  • 1
    That list resembles JSON, have you tried parsing it using a JSON parser? Such as jq Commented Dec 10, 2020 at 16:34

2 Answers 2

2

Use Perl to parse the Python output, like so (note single quotes around the string, which contains double quotes inside):

array=( $( echo '["127.0.0.1:14550","127.0.0.1:14551"]' | perl -F'[^\d.:]' -lane 'print for grep /./, @F;' ) )
echo ${array[*]}

Output:

127.0.0.1:14550 127.0.0.1:14551

Alternatively, use jq as in the answer by 0stone0, or pipe its output through xargs, which removes quotes, like so:

array=( $( echo '["127.0.0.1:14550","127.0.0.1:14551"]' | jq -c '.[]' | xargs ) )

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.
-F'[^\d.:]' : Split into @F on any chars other than digit, period, or colon, rather than on whitespace.

print for grep /./, @F; : take the line split into array of strings @F, select with grep only non-empty strings, print one per line.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches

Sign up to request clarification or add additional context in comments.

Comments

2

One option is to treat the string as , and use to parse it:

jq -rc '.[]' <<< '["127.0.0.1:14550","127.0.0.1:14551"]' | while read i; do
    echo $i
done

127.0.0.1:14550

127.0.0.1:14551

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.