0

I have a bash script that tails a file for a string that contains either "CONNECT" or "DISCONNECT". Once such a string is found that string is then piped to a php sript.

Here is the bash script:

tail -f -n 1 /var/log/connections | grep -P -0 --line-buffered "\bCONNECTED\b|\bDISCONNECTED\b" | php -f $SCRIPT_DIR/connections.php

And here is the php script:

#!/usr/bin/php
<?php

while ( false !== ( $connection_status = fgets ( STDIN ) ) )
{
    $get_status = preg_match ( "/\bCONNECTED\b|\bDISCONNECTED\b/", @$connection_status, $status_match ) ;

    foreach ( $status_match as $status )
    {
        switch ( $status )
        {
            case "CONNECTED": //If the string that got passed to this script (from the BASH script) contains CONNECTED
            {
                print ( "we are connected\r\n" ) ;
            }
            case "DISCONNECTED": //If the string that got passed to this script (from the BASH script) contains DISCONNECTED
            {
                print ( "we are disconnected\r\n" ) ;
            }
        }
    }
}
?>

DISCONNECT works as expected but with CONNECT it returns both "we are connected" and "we are disconnected"

1 Answer 1

2

Every case requires a break to stop it from running, not {}.

case "CONNECTED": //If the string that got passed to this script (from the BASH script) contains CONNECTED
     print ( "we are connected\r\n" ) ;
break;
case "DISCONNECTED": //If the string that got passed to this script (from the BASH script) contains DISCONNECTED
     print ( "we are disconnected\r\n" ) ;
break;

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found whose expression evaluates to a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

https://www.php.net/manual/en/control-structures.switch.php

Sign up to request clarification or add additional context in comments.

2 Comments

How foolish of me to have missed that. Thank you
Your foreach also could be removed and you could just use two ifs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.