为什么 grep 只返回一行?

为什么 grep 只返回一行?
#!/bin/bash

while true; do
    trap break SIGINT
    ping -w 5 10.0.0.1 | { trap '' SIGQUIT
        ts '%Y-%m-%d %H:%M:%S |' |
        grep -E 'PING|packets|rtt' | { read grep_out
            echo $grep_out
            # echo "INSERT INTO test VALUES($grep_out);EXIT;" |
            # mysql --user=user --password=pass
        }
     }
done

预期输出:

2015-11-07 05:42:35 | PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.
2015-11-07 05:42:40 | 5 packets transmitted, 5 received, 0% packet loss, time 4005ms
2015-11-07 05:42:40 | rtt min/avg/max/mdev = 16.385/133.707/471.837/174.004 ms
2015-11-07 05:42:40 | PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.

实际产量:

2015-11-07 05:42:35 | PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.
2015-11-07 05:42:40 | PING 10.0.0.1 (10.0.0.1) 56(84) bytes of data.

答案1

grep返回多行就好了:

$ while true; do
 trap break SIGINT
 ping -w 5 localhost | { trap '' SIGQUIT
 ts '%Y-%m-%d %H:%M:%S |' |
 grep -E 'PING|packets|rtt'
 }
done
2015-11-07 17:28:50 | PING localhost (127.0.0.1) 56(84) bytes of data.
2015-11-07 17:28:55 | 6 packets transmitted, 6 received, 0% packet loss, time 4998ms
2015-11-07 17:28:55 | rtt min/avg/max/mdev = 0.027/0.035/0.042/0.005 ms
2015-11-07 17:28:55 | PING localhost (127.0.0.1) 56(84) bytes of data.
2015-11-07 17:29:00 | 6 packets transmitted, 6 received, 0% packet loss, time 4999ms
2015-11-07 17:29:00 | rtt min/avg/max/mdev = 0.024/0.040/0.052/0.009 ms
2015-11-07 17:29:00 | PING localhost (127.0.0.1) 56(84) bytes of data.

问题在于read foo; echo foo你正在做不必要的事情:

grep -E 'PING|packets|rtt' | { read grep_out
    echo $grep_out
}

grep它将只读取的输出的一行。

因为您只需要在开头和结尾插入一个片段:

while true; do
    trap break SIGINT
    ping -w 5 10.0.0.1 | { trap '' SIGQUIT
        ts '%Y-%m-%d %H:%M:%S |' | {
            echo 'INSERT INTO test VALUES('
            grep -E 'PING|packets|rtt'
            echo ');EXIT;'
        } |
        mysql --user=user --password=pass
     }
done

例子:

$ while true; do
    trap break SIGINT
    ping -w 5 localhost | { trap '' SIGQUIT
        ts '%Y-%m-%d %H:%M:%S |' | {
            echo -n 'INSERT INTO test VALUES('
            grep -E 'PING|packets|rtt'
            echo -n ');EXIT;'
        } |
        cat
     }
done
INSERT INTO test VALUES(2015-11-07 17:48:02 | PING localhost (127.0.0.1) 56(84) bytes of data.
2015-11-07 17:48:07 | 6 packets transmitted, 6 received, 0% packet loss, time 4996ms
2015-11-07 17:48:07 | rtt min/avg/max/mdev = 0.029/0.037/0.046/0.008 ms
);EXIT;
INSERT INTO test VALUES(^C%                             

小心引用和其他 SQL 注入问题。

相关内容