shell脚本中关联数组及其遍历

shell中(version >= 4.1.2)也存在关联数组(associated array),跟PHP的关联数据很像。

查看shell版本

bash -version

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

一、定义关联数组

# 定义项目名和接口MAP
declare -A PROJECT_API_MAP
PROJECT_API_MAP=(
    ["energy.tv.weibo.cn"]="i.energy.tv.weibo.com"
)

注意:需要使用declare来声明,参考stackoverflow

declare -a declares an array indexed by integers.
declare -A declares an associative array indexed by strings.

不声明可能会提示如下错误

must use subscript when assigning associative array

二、遍历关联数组
获取关联数组全部键值可以使用如下变量

${!PROJECT_API_MAP[*]}

for循环遍历例子

#!/bin/bash

# 同步前端机项目配置文件到队列机
# salmonl@niliu.me
# 2019-07-24

# 定义项目名和接口MAP
declare -A PROJECT_API_MAP
PROJECT_API_MAP=(
    ["niliu"]="i.api.niliu.com"
)

# "${!PROJECT_API_MAP[*]}"不能加",不然变成字符串了,无法遍历
for project in ${!PROJECT_API_MAP[*]}
do
    mkdir -p /tmp/system/
    rm -f /tmp/system/$project
    curl --max-time 5 --connect-timeout 3 --retry 1 -s "http://${PROJECT_API_MAP[$project]}/system/SINASRV_CONFIG" -o /tmp/system/$project
    grep "SERVER_NAME" /tmp/system/$project &>/dev/null

    if [ $? -eq 0 ]; then
        cp /tmp/system/$project /data1/www/htdocs/$project/system/SINASRV_CONFIG
        chown nobody:nobody /data1/www/htdocs/$project/system/SINASRV_CONFIG
    else
        echo "[curl --max-time 5 --connect-timeout 3 --retry 1 -s \"http://${PROJECT_API_MAP[$project]}/system/SINASRV_CONFIG\"]"
        echo "$project fetch config error"
    fi
done

发表评论

电子邮件地址不会被公开。 必填项已用*标注