LoginSignup
0
0

More than 1 year has passed since last update.

Shell連想配列を勉強した

Posted at

初めに

今回は、最近衝撃だったshellの連想配列で学んだことをまとめてみます。
まさかShellにそんなことまで切ると思っていなかったのでかなり衝撃を受けました。

そもそもdeclareが有能すぎる

リードオンリーな -r

declare -r static="static content"
echo ${static} # static content
static="test" # bash: static: readonly variable

配列宣言の -a

array1=(1 2 3 4)
declare -a array2
array2=(2 3 4 5)
echo ${array1[@]} # 1 2 3 4
echo ${array2[@]} # 2 3 4 5

本命連想配列の -A

dict1=([a]=1 [b]=2)
declare -A dict2
dict2=([c]=3 [d]=4)
echo ${dict1[@]} # 1 2
echo ${dict2[@]} # 3 4

キーの配列は!で取得できる

echo ${!dict1[@]} # a b
echo ${!dict2[@]} # c d

実際に使った例

Zabbixトラッパーで使った時のデータ

/etc/zabbix/script/jstat/conf.sh
#!/bin/bash
Prefix=$1
ZabbixServerStr=`grep -e "Server=" test.conf|grep -e "^[^#]"`
temp_str=${ZabbixServerStr//=/ }
ZabbixServer=${temp_str[1]}
if [ "$Prefix" = "JAVA" ]; then
  OEM=(
    ["00"]="tomcat-abc"
    ["03"]="tomcat-cde"
    ["04"]="tomcat-def"
  )
  ServiceName=(
    ["00"]="tomcats@AAA.service"
    ["03"]="tomcats@CCC.service"
    ["04"]="tomcats@ddd.service"
  )
/etc/zabbix/script/jstatjstat.sh
Prefix=$1
ZabbixServer="127.0.0.1"
declare -A OEM=()
declare -A ServiceName()
source /etc/zabbix/script/jstat/conf.sh ${Prefix}
HostName=`uname -n`
TimeStamp=`date +%s`
TempFile="/tmp/Zsender_temp_$$"
CacheFile="/tmp/Zsender_cache_$$"
for key in ${OEM[@}; do
  PID=`ps aux|grep ${OEM[${key}]}|awk '{print($1)}'
  jstat -gc ${PID} > ${CacheFile}
  ProcessStatus=`systemctl status ${ServiceName[${key}]}|grep "Active:"|awk '{print($2)}'`
  echo ${Hostname} ${Prefix}${key}_process ${TimeStamp} ${ProcessStatus} >> ${TempFile}
  jstat_indexes=`cat ${CacheFile}|head -n 1`
  jstat_values=`cat ${CacheFile}|tail -n 1`
  for index in ${!jstat_indexes[@]};do
    echo ${Hostname} ${Prefix}${key}_${jstat_indexes[${index}]} ${jstat_values[${index}]} >> ${TempFile}
  done
done

zabbix_sender -z $ZabbixServer -T -i ${TempFile}
rm ${TempFile}
rm ${CasheFile}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0