1

I want to use curl command to get strings at cloud and parse them into a dictionary.

my shell code :

#!/bin/bash
#

URL=https://raw.githubusercontent.com/Nova-He/python/master/base_images

declare -A dic 

for x in $(curl -s $URL);do
 dic+=([$(echo $x |cut -d/ -f1)]="$(echo $x |cut -d/ -f2)")
done

# print all key 
echo ${!dic[*]}
# print all value
echo ${dic[*]}

using ./ run :

➜ ./get_ip_dic.sh
./get_ip_dic.sh: line 6: declare: -A: invalid option
declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
./get_ip_dic.sh: line 11: 10.114.12.26: syntax error: invalid arithmetic operator (error token is ".114.12.26")

but, using bash run :

➜ bash get_ip_dic.sh
10.134.34.228 10.134.34.227 10.114.12.27 10.114.12.26 10.129.35.188
b5be4856d837 2b8b028e6eeb b5be4856d837 b5be4856d837 2b8b028e6eeb

After searching online, I know that both methods are run in the subshell,there isn't different. So,I don't know what happened,thanks in advance.

Nova
  • 11
  • 6
  • Does [this question](https://stackoverflow.com/q/6047648/3266847) cover you? – Benjamin W. Apr 24 '19 at 15:54
  • May I, ahem, point to [my answer](https://stackoverflow.com/a/43948526/3266847) there. – Benjamin W. Apr 24 '19 at 15:55
  • BTW, `for x in $(curl ...)` is generally a bad idea (as is unquoted use of `${foo[*]}`). See [DontReadLinesWithFor](https://mywiki.wooledge.org/DontReadLinesWithFor), and consider running your code through http://shellcheck.net/ and following the wiki links in the warnings it raises. – Charles Duffy Apr 24 '19 at 16:02

1 Answers1

1

./get_ip_dic.sh uses the shebang, and so runs the script using /bin/bash. I'll assume you are on macOS, where /bin/bash is version 3.2.56, which doesn't support associative arrays.

bash get_ip_dic.sh, on the other hand, runs whichever bash appears first on your search path, which would appear to be a newer version of bash that you installed yourself.

chepner
  • 497,756
  • 71
  • 530
  • 681