【问题标题】:Why is using the ”./“ and ”bash“ to run the script result is different? [duplicate]为什么使用“./”和“bash”运行脚本结果不一样? [复制]
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 你是对的,谢谢。
猜你喜欢
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 2015-07-20
  • 2014-01-04
  • 1970-01-01
相关资源
最近更新 更多