使用shell脚本从一行中获取多个变量

问题描述 投票:1回答:1

我试图通过ping监控我的主机。主机信息在mysql表中。我使用fping命令代码如下

#/bin/sh

id=$(mysql -B --column-names=0 -uroot -pPassword -D monitor -e "SELECT ipv4 FROM nics WHERE icmp=1");

result=$(fping -c 10 $id |grep 'xmt/rcv/%loss');

#echo $result;

for line in $result;

do

echo $line

done

输出是

111.125.140.6 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 234/234/235

123.135.140.7 : xmt/rcv/%loss = 10/0/100%

111.125.140.1 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 230/231/231

111.125.130.2 : xmt/rcv/%loss = 10/10/0%, min/avg/max = 234/234/234

现在我想从每一行获得IP,丢失和平均记录,并在新表中输入数据

提前致谢

mysql bash shell
1个回答
1
投票

使用while循环(而不是for循环)与awk

while read -r line
    do declare $(awk '{split($0,a,"[%/ ,]"); print \
    "ip="a[1],"send="a[8],"rec="a[9],"loss="a[10],"min="a[17],"avg="a[18],"max="a[19]}' <<< $line);
    ## variables created: [ip, send, rec, loss, min, avg, max]
    ## test with: echo $ip, $send, $rec, $loss, $min, $avg, $max
    ## now you can insert the variables into your new SQL table:
    echo "INSERT INTO newtable (IP,SEND,REC,LOSS,MIN,AVG,MAX) \
    VALUES ('$ip','$send','$rec','$loss','$min','$avg','$max');"
done< <(printf '%s\n' "$result") | mysql -uroot -pPassword foobar

这将声明您可以插入SQL的$line字符串中的各个变量。

© www.soinside.com 2019 - 2024. All rights reserved.