gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:23:24 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com