The following piece of code shows how to use dictionaries in shell scripts.
First use declare -A to define a dictionary. (At present, the declare command is used instead of the typeset command. These two commands use similar Shell declare and typeset commands : set variable attributes)
#!/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
The above code performs fixed assignment to score and cyclic assignment to scoreSumSt. Both ways are ok.
echo ${
!scoreSumSt[*]} 是打印字典中所有的keys
echo ${scoreSumSt[*]} 是打印字典中所有的value
The result of running the above code is as follows:
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
Case code:
#!/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