美文网首页
Mac环境下shell脚本中的map

Mac环境下shell脚本中的map

作者: asturelizhe | 来源:发表于2017-06-01 22:24 被阅读2351次

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"

相关文章

  • Mac环境下shell脚本中的map

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

  • mac终端下运行shell脚本

    From: 在mac下编写shell脚本并执行 一些资料 Shell教程-for 菜鸟教程 Shell脚本编程30...

  • Shell脚本操作-1

    创建文件 一般shell脚本都是以.sh结尾的文件,我们如何创建一个shell脚本文件 首先在Mac环境下用命令t...

  • 指令随笔

    linux 修改shell脚本的编码 在window下编写的shell脚本编码为dos,在linux环境下不能直接...

  • 一些常用shell脚本

    mac使用shell脚本自动登录服务器 需要安装 brew reinstall expect 自动切换环境 自动更...

  • Shell环境变量

    bash shell中使用环境变量在内存中存储有关shell会话和工作环境的数据。以便程序或shell中运行的脚本...

  • shell脚本基础

    编写脚本 编程基础 shell脚本 创建shell脚本 变量 运算 测试 配置用户的环境

  • shell子进程修改父进程的环境变量值

    shell子进程修改父进程的环境变量值 脚本中的环境变量通过 export 导出,脚本中调用其他脚本使用这个变量 ...

  • Shell编程极简入门

    Shell编程不花里胡哨,一篇就够~ 一、基础入门 1.1 shell脚本的第一行代码 Linux环境下的任何脚本...

  • Mac下Shell脚本使用

    【原创博文,转载请注明出处!】准备学习下Shell命令,俗话说“好记性不如烂笔头”,做点笔记方便以后查找。详细学习...

网友评论

      本文标题:Mac环境下shell脚本中的map

      本文链接:https://www.haomeiwen.com/subject/sacyfxtx.html