-1

Using bash, I try to figure out how to fill a bidimentional array from the output of a curl command. 2 columns, but the number of line(s) is unknown. Let's say I get names and phone numbers separated by a space.

$ curl ${url}
Aname 000001
Bname 123456
CCname 000887
Dnname 354632
Xname 007008
...

All kind of help is welcome :) Thanks.

5
  • I don't think bash supports multidimensional arrays very well. Do you really need a 2D array or will a 1D associative array do? E.g. {Aname -> 00001, Bname -> 123456}, Commented Mar 31, 2018 at 10:30
  • Thanks for your reply, well ... I guess 1D may do .... Commented Mar 31, 2018 at 13:58
  • This may help then Commented Mar 31, 2018 at 14:28
  • A good question includes: input, output, sample script you tried to implement, what problem you are having. We will not write the code for you. Commented Mar 31, 2018 at 22:24
  • Modifying my command output on the fly to look like : [CCname]="000887" And using the solution found below to create an associative array. bash-associative-array-with-command-output Commented Mar 31, 2018 at 22:35

1 Answer 1

0

perhaps you can test with:

#!/bin/bash
declare -A myArray
while read key value; do 
    myArray["$key"]="$value"
done <<< $( curl "$url" )

# examples to use
echo "\$myArray has ${#myArray[@]} elements"
echo "here is the keys: ${!myArray[@]}"
echo "the whole array:"
for key in ${!myArray[@]}; do
    echo "$key => ${myArray[$key]}"
done

for simulation, you can use:

...
done <<< $( cat << "END"
Aname 000001
Bname 123456
CCname 000887
Dnname 354632
Xname 007008
END
)

and the result will be:

$myArray has 5 elements
here is the keys: Aname Xname CCname Bname Dnname
the whole array:
Aname => 000001
Xname => 007008
CCname => 000887
Bname => 123456
Dnname => 354632
Sign up to request clarification or add additional context in comments.

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.