# Shell : ArrayでCommand実行

Chanpu-·2021년 12월 22일

# Shell

목록 보기
4/10

作成理由:IPMI Serviceを使ってRemote ServerのPower statusを確認する

手順書に書かれてあるCommandはFor文でPrefixが同じで、4オクテットが連番であれば楽が、
バラバラのIPの場合は余計に時間が掛かるのが嫌でArrayで楽に検査しようと思った。

▸ 1個ずつ確認するコマンドはあるが、台数が多い場合それも面倒すぎる


01.Create IPMI_LIST array

# Create array for target server ipmi

IPMI_LIST=('1.0.0.1' '1.0.0.2' '1.0.0.3')

${IPMI_LIST[0]}
${IPMI_LIST[1]}
${IPMI_LIST[2]}

これでいけると思ったが、 Failed

./chi_test.sh: line 16: IPMI_LIST[0]: command not found
./chi_test.sh: line 17: IPMI_LIST[1]: command not found
./chi_test.sh: line 18: IPMI_LIST[2]: command not found

command not found (´ー`)ふむふむ、Bashでは文字列ではなくCommandとして認識されるようだ。

# Create array for target server ipmi

IPMI_LIST=('1.0.0.1' '1.0.0.2' '1.0.0.3')

echo "${IPMI_LIST[0]}"
echo "${IPMI_LIST[1]}"
echo "${IPMI_LIST[2]}"

これでArrayの中身を確認できた。
Arrayにコマンドを入れるのはどうかなと思ったが、可読性が良くなさそうなのでヤメだ。


02. Arrayを編集しやすく変更

次に確認したいのは、Array作成Codeを可読性よくすること!

IPMI_LIST=(
'1.0.0.1'
'1.0.0.2'
'1.0.0.3'
)

おお、これで修正が楽になった。

もしかしてシングルクォーテーションなしでも可能か試して見たが、イケる

#.Test 1
IPMI_LIST=(
1.0.0.1
1.0.0.2
1.0.0.3
)
#.Test 2
IPMI_LIST=(1.0.0.1 1.0.0.2 1.0.0.3)

どちらも同じ結果を出してくれる。
修正は楽な方が良いから、Test 1を採用('ω')ノ


03.For文でArrayのkeyをCommandで実行

GoogleでBashのForでArrayを使う方法を検索
ArrayのすべてのKeyを流すためには [@] を使う。

for i in "${arrayName[@]}"
do
   : 
# do whatever on "$i" here
done

まず、Echoでやってみよう

IPMI_LIST=(
1.0.0.1
1.0.0.2
1.0.0.3
)

for i in "${IPMI_LIST[@]}"
do
        echo "IPMI: $i"
done

Success(>_<)
では次に、作業で使うCommandのスクリプトを作成。

#!/bin/bash

IPMI_PREFIX=x.x.x.
IPMI_USER=xxxx
IPMI_PASS=xxxx

echo "

IPMI_PREFIX : $IPMI_PREFIX
IPMI_USER   : $IPMI_USER
IPMI_PASS   : $IPMI_PASS

"

# Create array for target server ipmi

IPMI_LIST=(
x.x.x.x
)

# ipmitool -U ${IPMI_USER} -P ${IPMI_PASS} -I lanplus -H <IPMI_LIST Key> power status;

for i in "${IPMI_LIST[@]}"
do
        echo -n "IPMI: $i >>> ";
        ipmitool -U ${IPMI_USER} -P ${IPMI_PASS} -I lanplus -H $i power status;
        # $i is Target Server's IPMI
done

echo ""&&echo ""

# ipmitool -U ${IPMI_USER} -P ${IPMI_PASS} -I lanplus -H $i power on;
# ipmitool -U ${IPMI_USER} -P ${IPMI_PASS} -I lanplus -H $i power off;

▸ 自分としては楽に作業してほしくて作ったが...これ楽じゃないの?

profile
何とかしちゃおう (*´ω`)

0개의 댓글