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"
网友评论