辞書を使ったシェルスクリプト

次のコードは、シェル スクリプトで辞書を使用する方法を示しています。

まず、declare -A を使用して辞書を定義します。(現在、typeset コマンドの代わりに、declare コマンドが使用されています。これら 2 つのコマンドは、同様のシェルの宣言コマンドと typeset コマンド(変数属性の設定) を使用します。)

#!/bin/bash
declare -A score
declare -A scoreSumSt
score=([zhangsan]=93 \
        [lisia]=90 \
        [wanger]=88 \
        [alian]=10)
echo ${
    
    !score[*]}
echo ${
    
    score[*]}
let scoreSum=1000
for sName in ${
    
    !score[@]}
do
        echo ${
    
    sName} :currScore=${
    
    score[${
    
    sName}]}
        let scoreSum=scoreSum+${
    
    score[${
    
    sName}]}
        echo ${
    
    scoreSum}
        scoreSumSt[${
    
    sName}]=${
    
    scoreSum}
done
echo ${
    
    !scoreSumSt[*]} #打印字典中所有的keys
echo ${
    
    scoreSumSt[*]}  #打印字典中所有的value

上記のコードは、score への固定割り当てと、scoreSumSt への循環割り当てを実行します。どちらの方法でも大丈夫です。

echo ${
    
    !scoreSumSt[*]} 是打印字典中所有的keys
echo ${scoreSumSt[*]}  是打印字典中所有的value

上記のコードを実行した結果は次のようになります。

alian lisia zhangsan wanger
10 90 93 88
alian :currScore=10
1010
lisia :currScore=90
1100
zhangsan :currScore=93
1193
wanger :currScore=88
1281
alian lisia zhangsan wanger
1010 1100 1193 1281

ケースコード:

#!/bin/bash
#所有服务器节点的hostname
declare -A dic
dic=([8001]="10.12.2.58" [8002]="10.12.2.58" [8003]="10.12.2.59" [8004]="10.12.2.59" [8005]="192.168.1.60" [8006]="192.168.1.60")

local_ip=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"​`
echo "### " date
echo "### local_ip: ${local_ip}"

for port in ${
    
    !dic[*]}
do 
    ip=${
    
    dic[${
    
    port}]}
    #echo ip: ${ip} ${port}
    if [ "$ip" = "$local_ip" ];
    then 
        local_count=`ps -ef|grep redis |grep $port | wc -l`
        if [ $local_count -eq 0 ];
        then
            echo "Start Local Redis Server $ip $port"
            redis-server /usr/local/redis/redis-cluster/$port/redis.conf
        else
            echo "Local Redis Server $ip $port already exists!"
        fi
    else
        count=`ssh root@$ip ps -ef|grep redis-server|grep -v grep|grep $port| wc -l`
        if [ $count -eq 0 ];
        then
            echo "Start Redis Server $ip $port"
            ssh root@$ip redis-server /usr/local/redis/redis-cluster/$port/redis.conf
        else
            echo "Redis Server $ip $port already exists!"
        fi
    fi    
done
exit 0

おすすめ

転載: blog.csdn.net/craftsman2020/article/details/128177757