php - Bash 到 php 正则表达式
问题描述
我有一个 bash 脚本,它尾随包含“CONNECT”或“DISCONNECT”的字符串的文件。一旦找到这样的字符串,该字符串就会通过管道传输到 php 脚本。
这是 bash 脚本:
tail -f -n 1 /var/log/connections | grep -P -0 --line-buffered "\bCONNECTED\b|\bDISCONNECTED\b" | php -f $SCRIPT_DIR/connections.php
这是php脚本:
#!/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按预期工作,但使用CONNECT它返回"we are connected"
和"we are disconnected"
解决方案
每个都case
需要 abreak
来阻止它运行,而不是{}
.
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;
为了避免错误,了解 switch 语句是如何执行的很重要。switch 语句逐行执行(实际上是逐语句执行)。一开始,没有代码被执行。只有找到一个 case 语句,其表达式的计算结果与 switch 表达式的值匹配时,PHP 才会开始执行这些语句。PHP 继续执行语句,直到 switch 块结束,或者它第一次看到 break 语句。如果你不在一个 case 语句列表的末尾写一个 break 语句,PHP 将继续执行下一个 case 的语句。
推荐阅读
- hadoop - 如何在直线命令中删除此警告:发现 Hive3 命名空间警告:HADOOP_YARN_HOME 无效
- .htaccess - 使用 .htaccess 打开 FTP 页面时出现 500 错误
- java - 以 ProcessBuilder 开始的进程停止提供数据
- laravel - Laravel:orderBy日期数据透视表
- python - 在 python 脚本中隐藏电子邮件密码
- r - 在 r 中绘制字典值
- mysql - 模棱两可的列名 laravel 5.6+
- c++ - 如何使用
标题 - javascript - 您可以将对象和数组一起分配给 JavaScript 中的变量吗?
- c#-4.0 - 将大量数据检索到数据表中并创建 csv 文件