シェルスクリプトのwhileループ内に変数を割り当てる

シェルスクリプトのwhileループ内に変数を割り当てる

whileループ内で変数を割り当てようとしますが、読み取りステートメント中にスクリプトが中断されます。

while read -r port  60720 60721 60722 60723 60724 

コードは次のとおりです。

 qmgrs=$($MQ_INSTALL_PATH/bin/dspmq | grep QMNAME | awk -F\( '{ print $2}'| awk -F\) '{ print $1}')

numqmgrs=$($MQ_INSTALL_PATH/bin/dspmq | grep QMNAME | wc -l)

strqmgrs=(${qmgrs})

i=$numqmgrs
arrayindex=0

while ((i != 0))
do
while read -r port  60720 60721 60722 60723 60724 ;do

  qmgrname=${strqmgrs[$arrayindex]}


echo "

this is the $port for the $qmgrname”


i=$((i-1))
  arrayindex=$((arrayindex+1))
done
done

希望の出力:

this is the 60720 for the apple”
this is the 60721 for the pear”
this is the 60722 for the mango”
this is the 60723 for the grape”
this is the 60724 for the blueberry”

ベストアンサー1

コマンドから取得したサーバー名とポート番号の静的リストをリンクしたいようです。

代わりにこれを行う:

PATH=$MQ_INSTALL_PATH/bin:$PATH

ports=( 60720 60721 60722 60723 60724 )
i=0

dspmq | sed -n '/QMNAME/{ s/.*(\([^)]*\)).*/\1/p; }' |
while read -r server && [ "$i" -lt "${#ports[@]}" ]; do
    printf 'Port on %s is %d\n' "$server" "${ports[i]}"
    i=$(( i+1 ))
done

これは本質的に望ましい操作ですが、条件付きの単一ループではなく2つのネストループを使用します。また、コードは、サーバー名を中間配列に保存せずに生成するコマンドパイプラインから直接読み込みます。

ポート番号を逆順に配布するには、次のようにします。

PATH=$MQ_INSTALL_PATH/bin:$PATH

ports=( 60720 60721 60722 60723 60724 )
i=${#ports[@]}

dspmq | sed -n '/QMNAME/{ s/.*(\([^)]*\)).*/\1/p; }' |
while read -r server && [ "$i" -gt 0 ]; do
    i=$(( i-1 ))
    printf 'Port on %s is %d\n' "$server" "${ports[i]}"
done

上記のすべての場合、式は配列の${#ports[@]}要素数に拡張されますports

sedコマンド

sed -n '/QMNAME/{ s/.*(\([^)]*\)).*/\1/p; }'

文字列を含む行の最初の角かっこ内の文字列が抽出されますQMNAME。次のように書くこともできます。

sed -n '/QMNAME/{ s/.*(//; s/).*//p; }'

おすすめ記事