polyphemus11
polyphemus11

Reputation: 113

How to grep a continuous stream from the CLI and exit if string found

I need to grep a continuous output stream from a ping-type output and check for the pattern "EOF" then quit if found. So far I have used the line buffering mode in grep and also have tried to output to a file, grep the file, but have not been able to get this to work. Last resort is to ask the community for help. Ideally I don't want a debug file and just want to have the code execute through pipes and if then statements.
"Apt-get install hping3" will get the hping3 package.

My current output is a endless stream of "EOF reached, wait some second than press ctrl+c" which is why I am trying to write to script to exit the loop on it's own instead of having to monitor the loop to press ctrl-c.

    #$1 - destination IP
    #$2 - signature
    #$3 - filename
    #$4 - data frame size
    CMD="hping3 $1 --icmp --sign $2 --file $3 -d $4 -u"
    EXP="EOF"
    while true
        do
        $CMD | grep -q --line-buffered -m 1 $EXP > ./debug.txt
            if grep "$EXP" ./debug.txt
            then
            echo "string found"
            fi
    exit
    done

Upvotes: 0

Views: 1614

Answers (1)

170730350
170730350

Reputation: 622

Try this:

hping3 $1 --icmp --sign $2 --file $3 -d $4 -u | sed '/EOF/q0'

What this does is that it will continually tail your log file and send the output to sed. Sed will search for the regex that you specify (you could add ^ if EOF is at the start of the line) and then exit with a code of 0 (the q0 sed command). You may use whatever exit code you prefer after the q command.

Upvotes: 1

Related Questions