![为输出的每一行分配一个变量并在 bash 中循环遍历它](https://linux22.com/image/101362/%E4%B8%BA%E8%BE%93%E5%87%BA%E7%9A%84%E6%AF%8F%E4%B8%80%E8%A1%8C%E5%88%86%E9%85%8D%E4%B8%80%E4%B8%AA%E5%8F%98%E9%87%8F%E5%B9%B6%E5%9C%A8%20bash%20%E4%B8%AD%E5%BE%AA%E7%8E%AF%E9%81%8D%E5%8E%86%E5%AE%83.png)
我有一个命令,它将有多行作为输出。我需要使用每一行作为另一个命令的源来处理它。我试图分配一个变量并循环它,但它失败了
这是命令行的输出
r_mqsc -m ABCD -r "DIS CHL(*) WHERE(SSLCIPH EQ TLS_RSA_WITH_AES_256_CBC_SHA)" -l |awk '/Connected/,0'|grep -v Connected |awk -F'SSLCIPH' '{print $1}'
CHANNEL(TO.MQ95XCAT02.SSL) CHLTYPE(CLUSRCVR)
CHANNEL(TO.MQ95XRB01.SSL) CHLTYPE(CLUSSDR)
CHANNEL(TO.MQ95XRC01.SSL) CHLTYPE(CLUSSDR)
CHANNEL(TO.MQ95XRL01.SSL) CHLTYPE(CLUSSDR)
CHANNEL(TO.MQ95XRN01.SSL) CHLTYPE(CLUSSDR)
CHANNEL(TO.XA.MQ95XCAT02.SSL) CHLTYPE(CLUSRCVR)
CHANNEL(TO.XB.MQ95XCAT02.SSL) CHLTYPE(CLUSRCVR)
CHANNEL(TO.XN.MQ95XCAT02.SSL) CHLTYPE(CLUSRCVR)
现在,每一行(完整的行)都需要输入到另一个命令中
像这样
r_mqsc -m ABCD -r "ALTER $VARIABLE SSLCIPH('123_ABC_XYZ')" -l
这是我的脚本,失败了
_chl="$(r_mqsc -m MQ95XCAT02 -r "DIS CHL(*) WHERE(SSLCIPH EQ TLS_RSA_WITH_AES_256_CBC_SHA)" -l |awk '/Connected/,0'|grep -v Connected |awk -F'SSLCIPH' '{print $1}')"
chlcnt=$(r_mqsc -m MQ95XCAT02 -r "DIS CHL(*) WHERE(SSLCIPH EQ TLS_RSA_WITH_AES_256_CBC_SHA)" -l |awk '/Connected/,0'|grep -v Connected |awk -F'SSLCIPH' '{print $1}'|wc -l)
echo "$_chl"
set -A strqmgrs ${_chl}
i=$chlcnt
arrayindex=0
while [ i -ne 0 ]
do
chl=${strqmgrs[$arrayindex]}
r_mqsc -m MQ95XCAT02 -r "ALTER $chl SSLCIPH('TLS_RSA_WITH_AES_256_CBC_SHA256')" -l
i=$((i-1))
arrayindex=$((arrayindex+1))
done
$chl 变量是这样的
ALTER CHLTYPE
--> 请注意,它只是在实际输出行中获取单词 CHLTYPE,而不是整行。
答案1
不要像编写 C 代码一样编写 bash 脚本(反之亦然)。
cmd |\
while IFS= read -r line
do
...
done
答案2
如果您需要在循环中保留变量设置,请像这样:
while read -r line
do
stuff
done < <( **command-line** )