【发布时间】:2019-09-13 23:40:02
【问题描述】:
我想使用 curl 命令在云端获取字符串并将它们解析成 一本字典。
我的外壳代码:
#!/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[*]}
使用./ 运行:
➜ ./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")
但是,使用bash 运行:
➜ 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
在网上搜索后,我知道这两种方法都是在子shell中运行的,没有什么不同。 所以,我不知道发生了什么,提前谢谢。
【问题讨论】:
-
this question 会覆盖你吗?
-
我可以,咳咳,指向my answer那里。
-
顺便说一句,
for x in $(curl ...)通常是个坏主意(${foo[*]}的未引用使用也是如此)。请参阅 DontReadLinesWithFor,并考虑通过 shellcheck.net 运行您的代码,并按照它引发的警告中的 wiki 链接。
标签: shell