Mac环境下shell脚本中的map

Linux 上服务执行脚本时运行正常,切换到Mac上之后如下脚本一直报错

Linux 上服务执行脚本时运行正常

[duan@dev ~]$ cat cmd.sh
#!/bin/bash
declare -A map=(["c"]="C" ["java"]="JAVA" ["go"]="GO")
echo ${map[go]}
[duan@dev ~]$ sh cmd.sh
GO
[duan@dev ~]$ echo $BASH_VERSION
4.2.46(1)-release

本地Mac 错误如下

bash-3.2$ sh cmd.sh
d.sh: line 2: declare: -A: invalid option
declare: usage: declare [-afFirtx] [-p] [name[=value] ...]
GO

Mac OS X 的默认Bash 是3.x版本,不支持map这种数据结构

bash-3.2$ help declare
declare: declare [-afFirtx] [-p] [name[=value] ...]
    Declare variables and/or give them attributes.  If no NAMEs are
    given, then display the values of variables instead.  The -p option
    will display the attributes and values of each NAME.

    The flags are:

      -a    to make NAMEs arrays (if supported)
      -f    to select from among function names only
      -F    to display function names (and line number and source file name if
        debugging) without definitions
      -i    to make NAMEs have the `integer' attribute
      -r    to make NAMEs readonly
      -t    to make NAMEs have the `trace' attribute
      -x    to make NAMEs export

    Variables with the integer attribute have arithmetic evaluation (see
    `let') done when the variable is assigned to.

    When displaying values of variables, -f displays a function's name
    and definition.  The -F option restricts the display to function
    name only.

    Using `+' instead of `-' turns off the given attribute instead.  When
    used in a function, makes NAMEs local, as with the `local' command.

所以有两种解决方案:

1. 升级bash到 4.x 以上版本

2. 用其他方式:比如 if elif 去到达相同的结果

echo $name
name="c"
if [ $name == "c" ]
then
   language="C"
elif [ $name == "java" ]
then
   language="JAVA"
elif [ $name == "go" ]
then
   language="GO"
else
   language="unknow"
fi
echo "language=$language"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,468评论 9 467
  • 1.创建文件夹 !/bin/sh mkdir -m 777 "%%1" 2.创建文件 !/bin/sh touch...
    BigJeffWang阅读 10,145评论 3 53
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,837评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,926评论 6 342
  • 安宁吃饭的时候对面坐了个很漂亮的女生。 她拿着考究的纸杯,含着上面的吸管。 低着头看手机。 染着的头发是安宁喜欢的...
    威德阅读 314评论 2 0