为什么使用“ ./”和“ bash”运行脚本结果不同?

时间:2019-04-24 15:50:06

标签: shell

我想使用curl命令在云端获取字符串并将其解析为 字典。

我的shell代码:

#!/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

在线搜索之后,我知道这两种方法都在子外壳中运行,没有什么不同。 所以,我不知道发生了什么事,谢谢。

1 个答案:

答案 0 :(得分:1)

./get_ip_dic.sh使用shebang,因此使用/bin/bash运行脚本。我假设您使用的是macOS,其中/bin/bash的版本是3.2.56,它不支持关联数组。

另一方面,

bash get_ip_dic.sh会运行您搜索路径中最先出现的bash,这似乎是您自己安装的bash的较新版本。

相关问题