bash - 如何检查bash中的子字符串

标签 bash apache

在这里查看一些类似的问题,但仍然卡住了。我的代码有什么问题?

check_conf_result=$(apachectl configtest 2>&1)
echo "Result of checking apache config: $check_conf_result"

if [[ "$check_conf_result" == *"Syntax OK"* ]]; then
        echo "Reload apache config"
        invoke-rc.d apache2 reload
else
        echo "Apache configure files wrong."
        #exit 1
fi

输出是:

Result of checking apache config: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
Syntax OK
/var/lib/dpkg/info/mybash.postinst: 114: [: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
Syntax OK: unexpected operator
Apache configure files wrong.

谢谢。

更新

下面的一段代码有效。 但是还是很奇怪为什么上面这段代码不行??? (顺便说一下,这是 debian/mybash.postinst 的一部分)。通过搜索“[[: not found”,我发现如果我使用“if [[ "$check_conf_result"== "Syntax OK" ]] 我应该使用“#!/bin/bash” ; 然后”。最后,我在下面使用了 case 语句。

        case "$check_conf_result" in
                *Syntax[[:space:]]OK*)
                echo "Reload apache config"
                invoke-rc.d apache2 reload
                ;;
                *)
                echo "Apache config files wrong."
                exit 1
                ;;
        esac

最佳答案

在 bash 中,单个方括号不执行模式匹配。为了使用它,你必须使用双方括号:

if [[ "$check_conf_result" == *"Syntax OK"* ]] ; then

这在 man bash 中有记录:

string1 == string2
string1 = string2

True if the strings are equal. = should be used with the test command for POSIX conformance. When used with the [[ command, this performs pattern matching as described above (Compound Commands).

测试:

#!/bin/bash
check_conf_result="Result of checking apache config: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1 for ServerName
Syntax OK"

if [[ "$check_conf_result" == *"Syntax OK"* ]] ; then
    echo Matches.
fi

关于bash - 如何检查bash中的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34419218/

相关文章:

linux - 解析 bash 脚本中的文本

javascript - 更新后的几分钟内服务器未分发更新的 javascript 文件

php - 在服务器上安装linux

apache - 重定向到Apache虚拟主机文件中的子文件夹

apache - 如何在单个AWS EC2实例上托管多个域和子域

git - 从预提交 Hook 中排除某些文件类型

java - 如何将上下箭 header value 传递给从 Java 调用的 bash 终端进程

python - 仅使用程序名称从命令行运行 Python 程序

linux - 具有 shell 扩展的 Systemd 单元配置

apache - 乘客错误 #2 无法统计 config.ru